分别通过成员函数和友元函数完成重载
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(double real =0,double imag=0):real(real),imag(imag){}; //构造函数,包含有参数的和没有参数的,默认为0,0
Complex(const Complex & p){real = p.real;imag = p.imag;} //复制构造函数
~Complex(){} //析构函数
//以下为成员函数
double getReal() const {return real;}
double getImag() const {return imag;}
void output(); //输出的函数
Complex operator+(const Complex& p);
//通过友元
friend Complex operator-(const Complex &p1,const Complex &p2);
private:
double real ,imag;
};
Complex Complex::operator+(const Complex& p) //计算加法的成员函数
{
return Complex(real+p.real,imag+p.imag);
}
void Complex::output() //输出的函数
{
if(imag >=0)
{
char flag;
flag ='+';
cout <<real <<flag<<imag <<'i' <<endl;
}
else
cout <<real <<imag <<'i' <<endl;
}
Complex operator-(const Complex &p1,const Complex &p2)
{
return Complex(p1.real-p2.real,p1.imag - p2.imag);
}
int main()
{
Complex a(3,4),b(4,-5),c ,d;
cout <<"输出a=";
a.output();
cout <<"输出b=";
b.output();
cout <<"输出a+b=";
c= a+b;
c.output();
cout <<"输出a-b=";
d= a-b;
d.output();
return 0;
}
运行结果: