C++에서는 사용자 정의 연산자를 사용할 수 있다. ::범위지정, . 멤버지정, .*멤버 포인터로 멤버 지정을 제외한 모든 연산자를 사용할 수 있다.
bool MyString::operator==(const MyString& str)
{
return !compare(str);
}
+연산자 함수를 구현연산 결과의 레퍼런스를 리턴한다면
a = b+c+b의 경우 사용자가 원하는 결과는a = 2b + c이지만 실제로 처리는(b.plus(c)).plus(b)가 되니(b+c)+(b+c)=2b+2c가 처리된다.(b에b+c가 들어가기 때문) 이를 방지하기 위해 값을 리턴하자
Complex Complex::operator+(const Complex& c) const
{
Complex temp(real + c.real, img + c.img);
return temp;
}
=연산자 함수를 구현a = b = c인 상황을 고려해 자기자신을 반환Complex& Complex::operator=(const Complex& c)
{
real = c.real;
img = c.img;
return *this;
}