C++ 赋值运算符重载

类的定义

class Test{
	int id;
public:
	Test(int i): id(i){
		cout << "obj_" << i << " created" << endl;
	}

	Test& operator= (const Test& right){
		if (this == &right){
			cout << "same object." << endl;
		} else {
			cout << "success." << endl;
			this->id = right.id;
		}
		return *this;
	}

	void print(){
		cout << id << endl;
	}
};

主函数

int main(){
	Test a(1), b(2);
	
	cout << "a = a: ";
	a = a;
	a.print();

	cout << "a = b: ";
	a = b;
	a.print();

	return 0;
}

结果

obj_1 created
obj_2 created
a = a: same object.
1
a = b: success.
2
posted @ 2019-03-29 19:27  黑冰5  阅读(274)  评论(0编辑  收藏  举报
runAll: function() { this.resetPreCode(); hljs.initHighlightingOnLoad(); // 重新渲染,添加语法高亮 hljs.initLineNumbersOnLoad(); // 为代码加上行号 }