멤버 함수로 구현된 이항 연산자(예: operator+
)는 항상 왼쪽 피연산자가 해당 클래스의 객체여야 합니다.
class Complex {
private:
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 멤버 함수로 구현된 더하기 연산자
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
};
이경우
a + b
는 a.operator+(b)
로 해석됩니다. 여기서 a
는 반드시 Complex
객체여야 합니다.Complex(1, 2) + Complex(3, 4)
와 같은 형태는 잘 작동합니다.2.0 + Complex(3, 4)
와 같은 형태는 작동하지 않습니다. 왜냐하면 2.0
은 Complex
객체가 아니므로 operator+
멤버 함수를 가지고 있지 않기 때문입니다.친구 함수로 구현된 연산자는 두 피연산자를 동등하게 취급하므로 피연산자의 순서에 더 유연합니다.
class Complex {
private:
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 친구 함수로 구현된 빼기 연산자
friend Complex operator-(const Complex& a, const Complex& b) {
return Complex(a.real - b.real, a.imag - b.imag);
}
};