class Complex
{
public:
Complex(double re = 0, double im = 0);
};
이것은 double 인자 하나만을 받을 수도 있고 따라서 double --> Complex의
형변환 연산자와 같은 역할을 할 수 있습니다. 그런데 operator+()가 멤버 함수라면
왼쪽 피연산자는 반드시 Complex형이어야 하지만 friend는 그렇지 않아도 됩니다.
Complex a, b;
double d;
a + b; // ok with both member and friend
a + d; // ok with both member and friend
d + a; // ok with friend but not with member
예를 들어 Complex 클래스에 다음과 같은 생성자가 있다고 합시다.
예를 들어 Complex 클래스에 다음과 같은 생성자가 있다고 합시다.
class Complex { public: Complex(double re = 0, double im = 0); };이것은 double 인자 하나만을 받을 수도 있고 따라서 double --> Complex의
형변환 연산자와 같은 역할을 할 수 있습니다. 그런데 operator+()가 멤버 함수라면
왼쪽 피연산자는 반드시 Complex형이어야 하지만 friend는 그렇지 않아도 됩니다.
코드의 효율과 유지보수성을 따져 적당한 방식으로 조합하면 됩니다.
class Complex { public: Complex operator+(const Complex&) const; Complex operator+(double) const; friend Complex operator+(double, const Complex&); };class Complex { public: Complex operator+(const Complex&) const; friend Complex operator+(double, const Complex&); };class Complex { public: friend Complex operator+(const Complex&, const Complex&); };댓글 달기