티스토리 뷰

연산자 오버로딩 

- 연산자 오버로딩이란 c++이 우리에게 제시하는 약속이다. (문법일 뿐이다) 



- 연산자 오버로딩은 기본 자료형 변수처럼 객체도 덧셈, 뺄셈과 같은 연산을 가능하게 한다.

  즉 객체를 기본자료형 데이터 처럼 취급할수 있도록 한다.

 

- 연산자 오버로딩을 하기 위해서는 operator 키워드와 연산자(+, ㅡ, * 등)를 묶어서 함수의 이름을 정의한다. 

  

- 연산자 오버로딩 방법에는 맴버함수에 의한 연산자 오버로딩전역함수에 의한 연산자 오버로딩이 있다.

 

- 동일한 자료형을 대상으로 맴버함수에 의한 오버로딩과 전역함수에 의한 오버로딩을 동시에 오버로딩할 경우, 

  맴버함수에 의한 오버로딩이 우선시 된다. 

 

맴버함수에 의한 연산자 오버로딩

맴버함수에 의한 연산자 오버로딩은 pos1 + pos2pos1.operator+(pos2)로 컴파일한다.

#include <iostream>
using namespace std;

class Point
{
private:
    int xpos, ypos;
public:
    Point(int x = 0, int y = 0) : xpos(x), ypos(y) {}
    void ShowPosition() const
    {
        cout << "[" << xpos << ',' << ypos << "]" << endl;
    }
    // 연산자 오버로딩
    Point operator+(const Point &ref)
    {
        Point pos(xpos+ref.xpos, ypos+ref.ypos);
        return pos;
    }
};

int main()
{
    Point pos1(3, 4);
    Point pos2(10, 20);
    // pos1.operator+(pos2) 호출
    Point pos3 = pos1 + pos2;

    pos1.ShowPosition();
    pos2.ShowPosition();
    pos3.ShowPosition();
}

실행결과:

 

- 연산자를 이용한 연산은 피연산자의 값을 변경하는 것이 아닌, 새로운 연산 결과를 만들어 내는 것이기 때문에 연산자 오버로딩한 함수에    도 const 선언을 하는것이 좋다.

 

 

전역변수에 의한 연산자 오버로딩

전역변수에 의한 연산자 오버로딩은 pos1 + pos2 를 operator+(pos1, pos2)로 컴파일한다.

#include <iostream>
using namespace std;

class Point
{
private:
    int xpos, ypos;
public:
    Point(int x = 0, int y = 0) : xpos(x), ypos(y) {}
    void ShowPosition() const
    {
        cout << "[" << xpos << ',' << ypos << "]" << endl;
    }

    friend Point operator+(const Point &pos1, const Point &pos2);
};

// 전역함수에 의한 연산자 오버로딩
Point operator+(const Point &pos1, const Point &pos2)
{
    Point pos(pos1.xpos+pos2.xpos, pos1.ypos+pos2.ypos);
    return pos;
}

int main()
{
    Point pos1(3, 4);
    Point pos2(10, 20);
    // operator+(pos1, pos2) 호출 
    Point pos3 = pos1 + pos2;

    pos1.ShowPosition();
    pos2.ShowPosition();
    pos3.ShowPosition();
}

문제 10-1 [두 가지 방법의 연산자 오버로딩]

문제 1

#include <iostream>
using namespace std;

class Point
{
private:
    int xpos, ypos;
public:
    Point(int x = 0, int y = 0) : xpos(x), ypos(y) {}
    void ShowPosition() const
    {
        cout << "[" << xpos << ',' << ypos << "]" << endl;
    }

    friend Point operator+(const Point &pos1, const Point &pos2);
    friend Point operator-(const Point &pos1, const Point &pos2);
};

// 전역함수에 의한 연산자 오버로딩
Point operator+(const Point &pos1, const Point &pos2)
{
    Point pos(pos1.xpos+pos2.xpos, pos1.ypos+pos2.ypos);
    return pos;
}

Point operator-(const Point &pos1, const Point &pos2)
{
    Point pos(pos1.xpos-pos2.xpos, pos1.ypos-pos2.ypos);
    return pos;
}

 

문제 2

#include <iostream>
using namespace std;

class Point
{
private:
    int xpos, ypos;
public:
    Point(int x = 0, int y = 0) : xpos(x), ypos(y) {}
    void ShowPosition() const
    {
        cout << "[" << xpos << ',' << ypos << "]" << endl;
    }
    
    // 증가된 맴버변수를 갖는 객체의 주소값 반환 
    Point& operator+=(const Point &ref)  
    {
        xpos += ref.xpos;
        ypos += ref.ypos;
        return *this;
    }

    Point& operator-=(const Point &ref)
    {
        xpos -= ref.xpos;
        ypos -= ref.ypos;
        return *this;
    }


};

 

문제 3

#include <iostream>
using namespace std;

class Point
{
private:
    int xpos, ypos;
public:
    Point(int x = 0, int y = 0) : xpos(x), ypos(y) {}
    void ShowPosition() const
    {
        cout << "[" << xpos << ',' << ypos << "]" << endl;
    }
    

    friend bool operator==(const Point &pos1, const Point &pos2);
};

bool operator==(const Point &pos1, const Point &pos2)
{
    if(pos1.xpos == pos2.xpos && pos1.xpos == pos2.ypos) return true;
    return false;
}

bool operator!=(const Point &pos1, const Point &pos2)
{
    // 위에서 정의한 operator== 를 이용
    if(pos1 == pos2) return false;
    return true;
}



문제 10-2 [단항 연산자 오버로딩]

문제 1

#include <iostream>
using namespace std;

class Point
{
private:
    int xpos, ypos;
public:
    Point(int x = 0, int y = 0) : xpos(x), ypos(y) {}
    void ShowPosition() const
    {
        cout << "[" << xpos << ',' << ypos << "]" << endl;
    }

    Point operator-() const
    {
        const Point pos(-xpos, -ypos);
        return pos;
    }
};

int main()
{
    Point pos1(1,3);
    Point pos2 = -pos1;
    pos2.ShowPosition();
}

 

문제 2

#include <iostream>
using namespace std;

class Point
{
private:
    int xpos, ypos;
public:
    Point(int x = 0, int y = 0) : xpos(x), ypos(y) {}
    void ShowPosition() const
    {
        cout << "[" << xpos << ',' << ypos << "]" << endl;
    }

    friend Point operator~ (const Point &ref);
};

Point operator~ (const Point &ref)
{
    Point pos(ref.ypos, ref.xpos);
    return pos;
}

int main()
{
    Point pos1(1,3);
    Point pos2 = ~pos1;
    pos2.ShowPosition();
}

 


연산자 오버로딩의 전위, 후위 연산

지금까지의 연산자 오버로딩은 전위 연산에 해당한다. (++num와 같은) 

후위 연산에 대한 연산자 오버로딩은 다음과 같이 표현한다.

 

후위증가: pos.operator++(int) 

후위감소: pos.operator--(int) 

 

여기서 int는 자료형과 관계 없이 전위 연산과 후위 연산을 구분하기 위한 표시일 뿐이다.

 

다음은 후위증가 연산의 연산자 오버로딩의 형태이다.


// 후위 연산 
const Point operator++(Point &ref, int) // int는 후위연산을 나타냄
{
    const Point retobj(ref); // 연산 전 객체 정보 저장 
    ref.xpos += 1; // 연산 진행 
    ref.ypos += 1;
    return retobj; // 연산 전 저장해놓은 객체 리턴 
}

코드에서 보이듯이 연산 전 객체 정보를 저장해놓고 맴버변수에 대한 연산을 진행한 후에,

연산 전 저장해놓은 객체를 리턴하는 방식으로 후위 연산을 구현할수 있다.

 

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/02   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
글 보관함