C++|运算符重载

#include <iostream>
using namespace std;

class CComplex
{
public:
	CComplex(int r = 0, int i = 0) :
		mreal(r), mimage(i) {}

	CComplex operator+(const CComplex &src)
	{
		/*CComplex comp;
		comp.mreal = this->mreal + src.mreal;
		comp.mimage = this->mimage + src.mimage;
		return comp;*/
		return CComplex(this->mreal + src.mreal, this->mimage + src.mimage);
	}

	CComplex& operator++()
	{
		mreal++;
		mimage++;
		return *this;
	}

	CComplex operator++(int)
	{
		CComplex comp = *this;
		mreal++;
		mimage++;
		return comp;
	}

	void operator+=(const CComplex &src)
	{
		mreal += src.mreal;
		mimage += src.mimage;
	}
	void show()
	{
		cout << "mreal:" << mreal <<" "<< "mimage" << mimage << endl;
	}
	private:
		int mreal;     //复数的实部
		int mimage;     //复数的虚部
		friend	CComplex operator+(const CComplex &a, const CComplex &b);
		friend ostream& operator<<(ostream &out, const CComplex &src);
		friend istream& operator >> (istream &in,  CComplex &src);

};

CComplex operator+(const CComplex &a, const CComplex &b)
{
	return CComplex(a.mreal + b.mreal, a.mimage + b.mimage);
}
ostream& operator<<(ostream &out, const CComplex &src)
{
	out << "mreal:" << src.mreal << "mimage" << src.mimage << endl;
	return out;
}
istream& operator >> (istream &in, CComplex &src)
{
	in >> src.mreal >> src.mimage;
	return in;
}



int main()
{
	CComplex comp1(10, 10);//定义实部和虚部都是10的复数comp1
	CComplex comp2(20, 20);//定义实部和虚部都是20的复数comp2
	CComplex comp3 = comp1 + comp2;
	comp3.show();
	/*显然编译器不知道两个复数类的对象如何相加,它会去CComplex类中找comp1的“+”方法,而把comp2当做实参
	因此需要些加法运算符的重载函数   comp1.operator+(comp2)*/
	CComplex comp4 = comp1 + 20;
	//comp4.operator+(20)  20从int -> CComplex   生成临时对象CComplex(20)
	comp4.show();
	//编译器做对象运算的时候,会调用对象的运算符重载函数(优先调用成员方法),如果没有成员方法,
	//就在全局作用域找合适的运算符重载函数

	CComplex comp5 = 20 + comp1;
	comp5.show();

	comp5 = comp1++;//单目运算符  不带参数 前置  带一个整形参数  后置
	comp5.show();
	comp1.show();

	comp5 = ++comp1;
	comp5.show();
	comp1.show();

	comp1 += comp2;
	//comp1.show();//对象的输出
	cout << comp1 << endl;
	cin >> comp1 >> comp2;
	cout << comp1 << comp2;


	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值