Triany
2011. 3. 14. 20:23
p + 3
==
p.operator+(3)
class Point {
private:
int x, y;
public:
Point(int _x=0, int _y=0):x(_x), y(_y){}
void ShowPosition();
void operator+(int val); //operator+라는 이름의 함수
};
void Point::ShowPosition()
{
cout<<x<<" "<<y<<endl;
}
void Point::operator+(int val)
{
x+=val;
y+=val;
}//operator+라는 이름의 함수
int main(void)
{
Point p(3,4);
p.ShowPosition();
//p.operator +(10);
p+10;
p.ShowPosition();
return 0;
} |
<연산자를 오버로딩하는 방법>
1. 멤버 함수에 의한 오버로딩
2. 전역 함수에 의한 오버로딩
1. 멤버함수에 의한 오버로딩
class Point {
private:
int x, y;
public:
Point(int _x=0, int _y=0):x(_x), y(_y){}
void ShowPosition();
void operator+(int val); //operator+라는 이름의 함수
Point operator+(const Point & p);
};
void Point::ShowPosition()
{
cout<<x<<" "<<y<<endl;
}
void Point::operator+(int val)
{
x+=val;
y+=val;
}//operator+라는 이름의 함수
Point Point::operator+(const Point & p)
{
Point temp(x+p.x, y+p.y);
return temp;
}
int main(void)
{
Point p1(1, 2);
Point p2(2, 1);
Point p3=p1+p2;
p3.ShowPosition();
return 0;
} |
2. 전역 함수에 의한 오버로딩
클래스에 있는 private로 선언된 변수를 직접 접근하기 위해선,
클래스 내에 friend 선언을 해 두어야 한다.
<오버로딩이 불가능한 연산자>
. .* :: ?: sizeof
++p -> p.operator++()
p++ -> p.operator++(int)