c15_11.cpp

来自「it can help you use C++ program we」· C++ 代码 · 共 32 行

CPP
32
字号
//用友元函数重载运算符"+"
class CComplex
{
public:
	CComplex(){ real = 0.0; image = 0.0; }
	CComplex(double rv) { real = rv; image = 0.0; }
	CComplex(double rv,double iv) { real = rv; image =iv;}
	friend CComplex  operator + (CComplex c1,CComplex c2); 
					//作为类的友元函数,重载加运算符,  
	~CComplex(){}
private:
	double	real;	//复数的实部
	double	image;	//复数的虚部 
};

CComplex operator +( CComplex c1,CComplex c2 )
{
	CComplex	temp;
	temp.real = c1.real + c2.real;
	temp.image = c1.image + c2.image;
	return temp;
}

int main( )
{
	CComplex c1(1,5),c2(3);
	c1 = c2+16;		//正确:被编译器解释为c1= operator+(c2,CComplex(16))
	c1 = 16+c2;		//正确:被编译器解释为c1= operator+( CComplex(16),c2)
	
	return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?