C++学习笔记之运算符重载

运算符重载

运算符重载的意义:
运算符的重载,让对象的运算表现得和内置类型一样
左边的对象,调用相应运算符的重载函数,把剩下的内容当作实参传递进去

运算符重载函数调用优先级:
编译器会从
1.成员方法找相应得运算符重载函数
2.从全局找运算符重载函数

重载示例:
// 复数类

class CComplex
{
public:
	//CComplex() CComplex(int) CComplex(int, int)
	CComplex(int r = 0, int i = 0)
		:mreal(r), mimage(i) {}
	~CComplex() {}
	// 复数对象相加
	// CComplex comp3 = comp1 + comp2;
	//CComplex operator+(const CComplex &src)
	//{
		//return CComplex(mreal + src.mreal
			//, mimage + src.mimage);
	//}

	CComplex operator++(int)
	{
		//CComplex temp = *this;
		//mreal++;
		//mimage++;
		//return temp;
		return CComplex(mreal++, mimage++);
	}
	CComplex& operator++()
	{
		mreal++;
		mimage++;
		return *this;
		//return CComplex(++mreal,++mimage); comp = ++comp1;
	}

	void operator+=(const CComplex &src)
	{
		mreal += src.mreal;
		mimage += src.mimage;
	}

	void show()
	{
		cout << "real:" << mreal << " image:" << mimage << endl;
	}
private:
	int mreal;
	int mimage;

	friend CComplex operator+(const CComplex &lhs,
		const CComplex &rhs);
};

// 全局得operator+  20 + comp1
CComplex operator+(const CComplex &lhs,
	const CComplex &rhs)
{
	return CComplex(lhs.mreal + rhs.mreal, lhs.mimage + rhs.mimage);
}

int main()
{
	CComplex comp1(10, 10);
	CComplex comp2(20, 20);
	//comp1.operator+(comp2);
	//CComplex operator+(const CComplex &comp2);
	CComplex comp3 = comp1 + comp2;
	comp3.show();

	// 20+comp1的实部上去
	// comp1.operator+(const CComplex &src)
	comp3 = comp1 + 20; // int => CComplex(int) 
	comp3.show();

// ::operator+(20, comp1);     
comp3 = 20 + comp1;
comp3.show();

// CComplex operator++(int)
comp2 = comp1++;  //operator++(int)后 operator++()前
comp1.show();
comp2.show();
comp2 = ++comp1;
comp1.show();
comp2.show();

comp2 += comp1; // operator+=
// ::operator<<(cout, comp1)  => CComplex得operator<<  operator>>运算符得重载函数
cout << comp1 << endl;
cout << comp2 << endl;

return 0;
}

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