demo_operator_02_e.cpp

来自「对于一个初涉VC++的人来书」· C++ 代码 · 共 100 行

CPP
100
字号

//************************************************
// 定义复数类,重载运算符为类的成员函数
// 重载二元运算符加"+",减"-",赋值"="
// 重载一元运算符求负"-"
//************************************************

# include <iostream.h>

class Complex
{
public:
	Complex(double r=0,double i=0);
	Complex(const Complex & other);
	void display();
	Complex operator + (const Complex & other);
	Complex operator - (const Complex & other);
	Complex operator - ();
	Complex operator = (const Complex & other);
protected:
	double real,image;
};

Complex::Complex(double r,double i)
{
	real=r;
	image=i;
	return;
}

Complex::Complex(const Complex & other)
{
	real=other.real;
	image=other.image;
	return;
}

void Complex::display()
{
	cout<<real;
	if(image>0) cout<<"+"<<image<<"i";
	if(image<0) cout<<image<<"i";
	cout<<endl;
	return;
}

Complex Complex::operator + (const Complex & other)
{
	Complex temp;

	temp.real=real+other.real;
	temp.image=image+other.image;
	return temp;
}

Complex Complex::operator - (const Complex & other)
{
	Complex temp;

	temp.real=real-other.real;
	temp.image=image-other.image;
	return temp;
}

Complex Complex::operator - ()
{
	Complex temp;

	temp.real=-real;
	temp.image=-image;
	return temp;
}

Complex Complex::operator = (const Complex & other)
{
	real=other.real;
	image=other.image;
	return *this;
}

int main()
{
	Complex c1(1,2),c2(2),c3(c1);

	c1.display();
	c2.display();
	c3.display();

	c1=c1+c2+c3;
	c1.display();

	c2=-c3;
	c2.display();

	c3=c2-c1;
	c3.display();

	return 0;
}

⌨️ 快捷键说明

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