43

A friend function is not a member but can access private members. It is often used for operator overloading such as <<.

C++ 15 lines
class Complex {
    int re, im;
public:
    Complex(int r = 0, int i = 0) : re(r), im(i) {}

    Complex operator+(const Complex &o) const {     // member operator
        return Complex(re + o.re, im + o.im);
    }
    friend ostream& operator<<(ostream &out, const Complex &c) {
        return out << c.re << " + " << c.im << "i";
    }
};

Complex a(2, 3), b(1, 4);
cout << a + b;    // 3 + 7i