#include <stdio.h>
/*
如果赋值操作符不返回引用代码也能编译通过
但会增加调用copy构造函数的开销(因为返回局部对象会调用拷贝构造函数)。
返回引用的话能减少调用copy构造函数
(effective Item10)
*/
class A {
public:
A &operator=(const A& rhs) {
printf("operator:%d\n", this->mem_v);
this->mem_v = rhs.mem_v;
return *this;
}
A(int mem) { //构造函数
mem_v = mem;
printf("init_A:%d\n", mem);
}
A(const A& C) { //拷贝构造函数
this->mem_v = C.mem_v;
printf("init_copy_A:%d\n", this->mem_v);
}
void get_memV() {
printf("self.mem_v:%d\n", this->mem_v);
}
void set_memV(int temp_v) {
this->mem_v = temp_v;
}
private:
int mem_v;
};
int main() {
A a(0);
A b(1);
A c(2);
c = b = a;
a.get_memV();
b.get_memV();
c.get_memV();
a.set_memV(4);
a.get_memV();
b.get_memV();
c.get_memV();
return 0;
}