第三十八节 C++ 运算符重载 - 双目运算符

时间:2021-01-01 02:13:54
#include <iostream>
using namespace std;

/* 运算符重载 -- 双目运算符 a+b, a+=b, a==b, a<b... 
 * 格式: 
 * 1 全局函数或静态成员函数: return_type operator symbol(param1,param2
 * 2 类成员: return_type operator symbol(param1),另一个参数是类的属性 
*/

class  Base {
private:
	unsigned int numBase;
public:
	/*operator a+b 的实现*/
	Base operator + (int input) {
		Base newBase(numBase + input);
		return newBase; 
	}

	/*operator a+=b 的实现*/
	Base& operator += (int input) {
		numBase += input;
		return *this; //this指当前对象的地址,*this指当前对象
	}

	/*operator a+=b 的实现*/
	bool operator == (Base& input) {
		if (numBase == input.numBase)
			return true;
		return false; 
	}
	
	/*访问属性numBase的接口*/
	void getNumBase() {
		cout << "    The Base num = " << numBase << endl;
	}

	Base(unsigned int initNum) : numBase(initNum) { 
		cout << "    Base constructor, init num = " << numBase << endl; }
//	~Base() { cout << "~Base deconstructor" << endl; }

};


int main()
{
	cout << "--- Create new object ---" << endl;
	Base Object(10); //栈上实例化对象
	Object.getNumBase();  //numBase = 10

	cout << "--- a+b ---" << endl;
	Base Object2(Object + 10);
	Object2.getNumBase();  //numBase = 20

	cout << "--- a+=b ---" << endl;
	Object2 += 10;
	Object2.getNumBase();  //numBase = 30

	cout << "--- Create new object" << endl;
	Base Object3(30);

	cout << "--- a==b ---" << endl;
	if (Object2 == Object3)
		cout << "    Object2 == Object3" << endl;

	return 0;
}

output:

--- Create new object ---
    Base constructor, init num = 10
    The Base num = 10
--- a+b ---
    Base constructor, init num = 20
    The Base num = 20
--- a+=b ---
    The Base num = 30
--- Create new object
    Base constructor, init num = 30
--- a==b ---
    Object2 == Object3