nakka soft world !

연산자 재정의 개념 본문

프로그래밍언어/C++

연산자 재정의 개념

nakka 2017. 3. 19. 01:24
728x90

연산자 재정의 개념.


1. 기본

class Point

{

private:

int x, int y;

public:

Point(int a = 0, int b = 0) : x(a), y(b) {}

void print() const ( cout << x << "," << y <<endl;


friend Point opretator+(const Point& p1, const Point& p2);

};

Point opretator+(const Point& p1, const Point& p2)

{

Point ret(p1.x + p2.x, p1.y + p2.y);

return ret;

}  // 일반함수로 구현하기

int main()

{

int n = 1 + 2;

Point p1(1, 1);

Point p2(2, 2);


Point p3 = p1+p2; // operator+(p1, p2);


p3.print();

}

// 더하기도 함수로 만들 수 있다.


2. 심화

class Point

{

private:

int x, int y;

public:

Point(int a = 0, int b = 0) : x(a), y(b) {}

void print() const ( cout << x << "," << y <<endl;

Point opretator+(const Point& p)

{

Point ret( x+ p.x, y + p.y)

return ret;

} // 멤버함수로 구현 하기.

};

int main()

{

int n = 1 + 2;

Point p1(1, 1);

Point p2(2, 2);


Point p3 = p1+p2;     // 컴파일러는 두가지 함수를 찾는다.

// 1. p1.operator+(p2) 를 찾는다.

// 2. operator+(p1, p2)


p3.print();

}


// 일반 함수와 멤버 함수 두 개가 공존 한다면?

// 멤버 함수가 우선시 됨. 혹시 멤버 함수가 없으면 일반함수가 호출된다.

// 둘중에 무엇이 좋은 가는

   // 연산 후에 객체의 상태가 변경되면 멤버 함수가 좋고

   // ++n;

   // 연산 후에 객체의 상태가 변경되지 않고 값만 리턴한다면 일반 함수가 좋다.

   // n1 + n2;



728x90

'프로그래밍언어 > C++' 카테고리의 다른 글

증가/감소 연산자 재정의  (0) 2017.03.19
cout & ostream  (0) 2017.03.19
this  (0) 2017.03.19
상수 멤버 함수 (const member function)  (0) 2017.03.19
정적 멤버 데이터 (static member data)  (0) 2017.03.17
Comments