类的定义

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

相关文章:

  • 2021-10-12
  • 2022-01-10
  • 2022-12-23
  • 2021-07-04
  • 2021-07-14
  • 2022-12-23
  • 2021-06-17
猜你喜欢
  • 2022-02-18
  • 2021-05-31
  • 2021-05-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案