함수와 달리
연산자는 피연산자의 개수/타입이 고정되어 있음.
연산자 함수도 멤버함수, 전역함수로 각각 만들 수 있다.
멤버 연산자 함수 version
전역 연산자 함수 version
그럼 무엇이 더 좋은가? 그런 거 없음. 심지어 둘 중 하나만 지원하는 경우도 있다.
#include <iostream>
using namespace std;
class Position
{
public:
Position operator+(const Position& arg)
{
Position pos;
pos._x = _x + arg._x;
pos._y = _y + arg._y;
return pos;
}
Position operator+(int arg)
{
Position pos;
pos._x = _x + arg;
pos._y = _y + arg;
return pos;
}
bool operator==(const Position& arg)
{
return _x == arg._x && _y == arg._y;
}
void operator=(int arg)
{
_x = arg;
_y = arg;
}
public:
int _x;
int _y;
};
Position operator+(int a, const Position& b)
{
Position ret;
ret._x = b._x + a;
ret._y = b._y + a;
return ret;
}
// 'operator='은(는) 멤버 함수여야 합니다. 컴파일 에러
// 두번째 인자로 대입하는 등 혼란이 있을 수 있기 때문에 문법적으로 막아둠.
void operator=(Position& a, int b)
{
a._x = b;
a._y = b;
}
int main()
{
Position pos;
pos._x = 0;
pos._y = 0;
Position pos2;
pos2._x = 1;
pos2._y = 1;
Position pos3 = pos + pos2;
pos3 = pos.operator+(pos2);
Position pos4 = pos3 + 1;
pos3.operator+(1);
Position pos5 = 1 + pos3;
operator+(1, pos3);
bool isSame = (pos3 == pos4);
Position pos6;
pos6 = 5;
//Position pos6 = 5; // int 하나 받는 생성자가 호출됨.
return 0;
}
복사 대입 연산자
기타
증감 연산자 ++ --
Position& operator=(positon& arg)
{
_x = arg._x;
_y = arg._y;
rteurn *this;
}
Position& operator++()
{
_x++;
_y++;
return *this;
}
Position operator++(int)
{
Position ret = *this;
_x++;
_y++;
return ret;
mov eax,dword ptr [ebp+8]
mov ecx,dword ptr [ret]
mov edx,dword ptr [ebp-18h]
mov dword ptr [eax],ecx
mov dword ptr [eax+4],edx
mov eax,dword ptr [ebp+8]
}
...
++(++pos3);
pos5 = pos3++;
push 0
lea eax,[ebp-150h]
push eax
lea ecx,[pos3]
call Position::operator++ (...)
push eax
lea ecx,[pos5]
call Position::operator= (...)