通过CComplex类的实现学习C++的运算符重载

注意点:

1,前置单目运算符在函数的参数列表中不加任何值

2,后置单目运算符需要在参数列表中加int告诉编译器这是后置单目运算符

3,

#include <iostream>
using namespace std;

class CComplex
{
public:
	CComplex(int r = 0, int i = 0)
		:_mreal(r)
		,_mimage(i)
	{
	}
	void operator=(const CComplex&obj)
	{
		this->_mreal = obj._mreal;
		this->_mimage = obj._mimage;
	}
	//指导编译器怎么做CComplex类对象的加法操作
	/*CComplex operator+(const CComplex&com)
	{
		return CComplex(this->_mreal + com._mreal,
			this->_mimage + com._mimage);
	}*/
	CComplex operator++(int)
	{
		return CComplex(this->_mreal++, this->_mimage++);
		/*CComplex comp = *this;
		this->_mimage++;
		this->_mreal++;
		return comp;*/
	}
	CComplex& operator++()
	{
		_mreal += 1;
		_mimage += 1;
		return *this;
	}
	void operator+=(const CComplex&rhs)
	{
		this->_mreal += rhs._mreal;
		this->_mimage += rhs._mimage;
	}
	void show() { cout << "real:" << _mreal << "image:" << _mimage << endl; }
private:
	int _mreal;
	int _mimage;
	friend CComplex operator+(const CComplex &lhs, const CComplex &rhs);
	friend ostream& operator<<(ostream&out, const CComplex&src);
	friend istream& operator>>(istream&in, CComplex&src);
};
istream& operator>>(istream&in, CComplex&src)
{
	int a, b;
	in >> a >> b;
	src._mreal = a;
	src._mimage = b;
	return in;
}
ostream& operator<<(ostream&out, const CComplex&src)
{
	out << "real:" << src._mreal << "image:" << src._mimage << endl;
	return out;
}
CComplex operator+(const CComplex &lhs, const CComplex &rhs)
{
	return CComplex(lhs._mreal + rhs._mreal, lhs._mimage + rhs._mimage);
}
int main()
{
	CComplex c1(1, 2);
	CComplex c2(2, 3);
	CComplex c4;
	c4 = c1+c2;
	c4.show();
	c4 = c1 + 20;
	c4.show();
	c4 = 30 + c2;
	c4.show();
	CComplex c5;
	c5 = c4++;
	c5.show();

	c5 = ++c4;
	c5.show();

	c5 += c4;
	c5.show();
	cout << "++++++++++++++++++++++++++++++" << endl;

	cout << c5;

	CComplex c6;
	cin >> c6;
	cout << c6;
	return 0;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值