c15_10.cpp

来自「这是编程之道C-C++中的源代码,很简练,可以用于相关教学和重新熟悉C-C++时」· C++ 代码 · 共 31 行

CPP
31
字号
//用成员函数重载运算符"+"
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;}
	CComplex  operator + (const CComplex&);		//重载的加运算符
	~CComplex() {};
private:
	double	real;		//复数的实部
	double	image;		//复数的虚部
};

CComplex  CComplex::operator +(const CComplex& c)
{
	CComplex	temp;
	temp.real = real + c.real;
	temp.image = image + c.image;
	return temp;
}

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

	return 0;
}

⌨️ 快捷键说明

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