运算符重载友元函数的调用

img

不理解关于友元函数,函数有两个参数,但是在调用时,可以直接c1+c2,结果和operator(c1,c2)一样。

#include<iostream>
using namespace std;
class Complex {//复数类
    friend Complex operator+(const Complex& c1, const Complex& c2);
    friend void show(const Complex& c);
private:
    double real;//实部
    double imag;//虚部
public:
    Complex() { real = imag = 0; }
    Complex(double re) { real = re;imag = 0; }
    Complex(double re, double im) { real = re;imag = im; }
};
Complex operator + (const Complex& c1, const Complex& c2) {
    return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
void show(const Complex& c) {
    if (c.imag > 0)
    {
        cout << c.real << "+" << c.imag << "i";
    }
    else if (c.imag < 0)
    {
        cout << c.real << c.imag << "i";
    }
    else
    {
        cout << c.real;
    }
}
int main() {
    Complex c1(4.0, -1.0);
    Complex c2(-1.0, 3.0);
    Complex c4;
    c4 = c1 + c2;
    show(operator+(c1, c2));//和c4输出结果一样  operator+(a,b)=a+b;?
    show(c4);
    show(operator+(c1, 9.0));
    return 0;
}