cppTest-7.1:運算符重載

/**
 *cppTest-7.1:運算符重載
 *
 *author 煒sama
 */
#include<iostream.h>
class complex{
	float real;
	float imag;
public:
	complex(float r=0,float i=0){ real=r; imag=i; }
	void show(){ cout<<real<<"+"<<imag<<"j"<<endl; }
	complex operator+(complex &c);
};
complex complex::operator+(complex &c)
{
	float r,i;
	r=real+c.real;
	i=imag+c.imag;
	return complex(r,i);
}
void main()
{
	complex x(5,2);
	complex y(4,3);
	complex z;
	z=x+y;
	z.show();
	//這個程序的輸出結果是9+5j,這表明語句z=x+y完成了對複數的加運算。
	//這個語句的執行過程可以解釋成:z=operator+(x,y);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章