//重载函数作为友元函数
#include <iostream>
using namespace std;
class complex
{
public:
complex (){real=0,image=0;}
complex (double r,double i){real=r,image=i;}
friend complex operator +(complex&c1,complex &c2); ///声明重载双目运算符“+”的函数,函数声明为友元函数,C1不可省
//“运算符左侧可以为其他类型的数据。”
void display();
private:
double real,image;
};
complex operator+(complex &c1, complex &c2) ///
{
return complex(c1.real+c2.real,c1.image+c2.image); ///返回complex 的数据
}
void complex ::display() ///输出复数的格式。
{
cout<<"("<<real<<","<<image<<"i"<<")"<<endl;
}
int main()
{
complex c1(1,2),c2(3,4),c3;
c3=c1+c2;
cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
cout<<"c3=";
c3.display();
return 0;
return 0;
}
对运算符重载的函数2
最新推荐文章于 2020-12-21 20:41:39 发布