测试代码
#include<iostream>
#include<string>
using std::ostream;
using std::cin;
using std::cout;
using std::endl;
class complex{
public:
complex(double a=0.0,double b=0.0):a(a),b(b){
cout<<"构造函数被调用!"<<endl;
}
~complex(){
cout<<"析构函数被调用!"<<endl;
}
friend complex operator + (const complex &c1,const complex &c2)
{
return complex((c1.a+c2.a),(c1.b+c2.b));
}
friend complex operator - (const complex &c1,const complex &c2)
{
return complex((c1.a-c2.a),(c1.b-c2.b));
}
friend ostream & operator << (ostream &out ,const complex &c)
{
out<<"("<<c.a<<","<<c.b<<")"<<endl;
return out;
}
private:
double a;
double b;
};
int main()
{
complex a1(2,2);
complex a2(4,4);
complex a3;
a3=a1+a2;
cout<<a3;
return 0;
}
程序运行界面