연산자 오버로딩

 - 사용자 정의 타입에도 연산자를 사용할 수 있게 하는 문법

 

#include <iostream>
using namespace std;
class Point {
    int x;
    int y;
    
public:
    Point(int _x = 0, int _y = 0) : x(_x), y(_y) {}
    void Print() const { cout << x << ',' << y << endl; }
    const Point operator+(const Point& arg) const {
        Point pt;
        pt.x = this->x + arg.x;
        pt.y = this->y + arg.y;
        
        return pt;
    }
    
};

int main() {
    Point p1(2,3), p2(5,5);
    Point p3;
    
    p3 = p1 + p2; //컴파일러가 p1.operator+(p2)로 변해서 인식함
    p3.Print();
    p3 = p1.operator+(p2);
    p3.Print();

    //전위 연산자와 후위 연산자 구별 하는 방법
    //후위 연산자는 아무 의미 없는 값을 넣어서 구별 한다.
    ++p1; //p1.operator++;
    p2++; //p2.operator++(0);
    



    return 0;
}
 

위 연산자 오버로딩 예제는 멤버함수를 이용한 연산자 오버로딩

 

전역 함수를 이용한 연산자 오버로딩을 사용하고 싶으면 

 

operator+(p1,p2); 이런씩으로 구현을 해야 한다.

+ Recent posts