使用友元函数形式进行运算符重载
更新:HHH   时间:2023-1-7


#include <iostream>

using namespace std;

class Complex
{
private:
    int real;
    int p_w_picpath;
public:
    Complex(int real=0,int p_w_picpath=0):real(real),p_w_picpath(p_w_picpath)
    {
        cout<<"Complex::Complex():"<<this<<endl;
    }
    Complex(const Complex &x):real(x.real),p_w_picpath(x.p_w_picpath)
    {
        cout<<"Complex::Complex(Complex &):"<<this<<endl;
    }
    ~Complex()
    {
        cout<<"Complex::~Complex():"<<this<<endl;
    }
    friend Complex operator+(Complex &a,Complex &b);

    friend Complex operator-(Complex &a,Complex &b);

    void show();
};
Complex operator+(Complex &a,Complex &b)
{
    return Complex(a.real+b.real,a.p_w_picpath+b.p_w_picpath);
}
Complex operator-(Complex &a,Complex &b)
{
    return Complex(a.real-b.real,a.p_w_picpath-b.p_w_picpath);
}
void Complex::show()
{
    cout<<real;
    if(p_w_picpath>0)
        cout<<"+";
    cout<<p_w_picpath<<"i"<<endl;
}
int main(int argc, char *argv[])
{
    Complex a(10,20);
    Complex b(70,80);
    Complex c=a+b;
    Complex d=a-b;
    a.show();
    b.show();
    c.show();
    d.show();
    return 0;
}

返回编程语言教程...