关于重载赋值操作符需要返回引用

来源:互联网 发布:藏族音乐软件 编辑:程序博客网 时间:2024/06/05 11:17
#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;}

0 0
原创粉丝点击