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

注意点:

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

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

3,

#include 
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;
}

 

你可能感兴趣的:(C++)