C++
연산자 오버로딩
猫猫
2014. 9. 12. 12:10
반응형
객체 operator+ (객체를 받는 객체) 함수
//결국엔 함수 호출이다.
//함수명은 정해져있다 operator기호
예제)
class sample{
int x;
int y;
public :
sample(){ x=0 , y=0;}
sample (int n1, int n2) { x = n1, y = n2;}
~sample() {}
void GetData(int &i, int &j) { i =x; j=y;}
sample operator+ (sample obj);
};
sample sample::operator +(sample obj)
//a+b == a.operator+ (b) 앞에있는 함수의 오퍼레이터
{
sample temp;
temp.x = x+obj.x;
temp.y = y+obj.y;
return temp;
}
void main()
{
sample a(10,10), b(5,2), c;
int x, y;
//c라는 객체에 a와 b객체를 더한 값을 집어넣고 싶다.
c = a+b;
// 하지만 이대로라면 에러가 난다. 그래서 operator+ 함수를 호출하여 +에기능을 부여한다.
}
반응형