第三十七节 C++ 运算符重载 - 单目运算符

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dddd0216/article/details/79962542
#include <iostream>
using namespace std;

/*运算符重载 -- 单目运算符 ++, --, *, -> 
 格式: return_type operator symbol(params list...) 
*/

class  Base {
private:
	unsigned int numBase;
public:
	/*operator ++i 的实现*/
	Base& operator ++ () {
		++numBase;
		return *this; //this指当前对象的地址,*this指当前对象
	}

	/*operator --i 的实现*/
	Base& operator -- () {
		--numBase;
		return *this; //this指当前对象的地址,*this指当前对象
	}

	/*operator i++ 的实现, 实现后++,需要在()加参数*/
	Base operator ++ (int) {
		Base CopyObject(numBase);
		++numBase;
		return CopyObject;
	}
	/*operator i-- 的实现, 实现后--,需要在()加参数*/
	Base operator -- (int) {
		Base CopyObject(numBase);
		--numBase;
		return CopyObject;
	}

	/*访问属性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 << "--- ++i, --i " << endl;
	++Object;   //先加后用
	++Object;
	Object.getNumBase();  //numBase = 12
	--Object;  //先减后用
	Object.getNumBase();  //numBase = 11

	cout << "--- i++, i-- " << endl;
	Object++;  //先用后加
	Object.getNumBase();  //numBase = 12
	Object--;
	Object.getNumBase();  //numbase = 11

	return 0;
}

output: 

--- Create new object
    Base constructor, init num = 10
    The Base num = 10
--- ++i, --i
    The Base num = 12
    The Base num = 11
--- i++, i--
    Base constructor, init num = 11
    The Base num = 12
    Base constructor, init num = 12
    The Base num = 11

阅读更多
想对作者说点什么?

博主推荐

换一批

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