将+、-(双目)重载为复数类的友元函数

源程序:

#include
class complex	//复数类声明
{
public:	//外部接口
	complex(double r=0.0,double i=0.0){ real=r; imag=i; }	//构造函数
	friend complex operator + (complex c1,complex c2);	//运算符+重载为友元函数
	friend complex operator - (complex c1,complex c2);	//运算符-重载为友元函数
	void display();	//显示复数的值
private:	//私有数据成员
	double real;
	double imag;
};
			
complex operator +(complex c1,complex c2)	//运算符重载友元函数实现
{	 
	return complex(c2.real+c1.real, c2.imag+c1.imag);
}

complex operator -(complex c1,complex c2)	//运算符重载友元函数实现
{
	return complex(c1.real-c2.real, c1.imag-c2.imag);
}

void complex::display()
{   cout<<"("< 
  

 

 

 

你可能感兴趣的:(C++程序设计)