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

#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

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dddd0216/article/details/79963098
个人分类: C++
所属专栏: C++基础
上一篇第三十七节 C++ 运算符重载 - 单目运算符
下一篇第三十九节 C++ 类型转换运算符 static_cast, dynamic_cast, reinterpret_cast, const_cast
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭