멤버 함수로 구현된 이항 연산자의 특징

멤버 함수로 구현된 이항 연산자(예: 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);
    }
};

이경우

image.png

친구 함수로 구현된 연산자는 두 피연산자를 동등하게 취급하므로 피연산자의 순서에 더 유연합니다.

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);
    }
};