【正确答案】#include<iostream>
using namespace std;
class complex{
public:
complex(){real=imag=0;}
complex(double r){real=r; imag=0;}
complex(double r, double i){real=r; imag=i;}
complex operator+(const complex&c);
friend void print(const complex&c);
private:
double real, imag;
};
inline complex complex::operator+(const complex&c)
{return complex(real+c.real, imag+c.imag);}
void print(const complex&c)
{if(c.imag<0)cout<<c.real<<c.imag<<'i';
else cout<<c.real<<'+'<<c.imag<<'i';}
void main(){
complex c1(2.5), c2(3.6, -1.2), c3;
c3=c1+c2; cout<<"c1+c2="; print(c3);
cout<<endl;
}
【答案解析】 采用成员函数的形式对复数加法运算“+”进行运算符重载。complex &c是形参表,c是类complex的引用对象,所以使用对象名。c.real、c.imag代表对象c的数据成员real、imag,用以完成两个复数的加法运算。