C++ : 연산자 오버로딩(1) - 기본
참고 : 열혈강의 C++ 프로그래밍 책
#include <iostream>
using namespace std;
class OperPoint
{
private:
int xpos, ypos;
public:
OperPoint(int x = 0, int y = 0) : xpos(x), ypos(y)
{ }
void ShowPosition() const
{
cout << '[' << xpos << ", " << ypos << ']' << endl;
}
// operator 키워드와 + 연산자를 묶어서 함수의 이름을 정의하면
// 함숨 이름 뿐만 아니라 연산자를 이용한 함수의 호출도 허용
// const를 선언하는 것은 피연산자의 값을 변경하기 않기 때문이다
OperPoint operator+(const OperPoint &ref)
{
OperPoint pos(xpos + ref.xpos, ypos + ref.ypos);
return pos;
}
};
// 테스트 함수
void Operator1()
{
OperPoint pos1(3, 4);
OperPoint pos2(10, 20);
OperPoint pos3 = pos1+pos2;
pos1.ShowPosition();
pos2.ShowPosition();
pos3.ShowPosition();
}
댓글
댓글 쓰기