昨天写代码时用了容器 vector,map.其中元素是自己定义的。比如:
- class test
- {
- public:
- test(){a = 0;b= 0;}
- //test(const test& other){a = other.a;b = other.b;}
- test(test& other){a = other.a;b = other.b;}
- test& operator=(const test& other){a = other.a;b = other.b;return *this; }
- ~test(){}
- int a;
- int b;
- };
容器无法push_back()/insert()
报错类似于"An object or reference of type "test" cannot be initialized with an expression of type "const test""..
原来
- void vector<_Ty, _Ax>::insert(iterator _P, size_type _M, const _Ty& _X)
- {_Ty _Tx = _X;
- ......
- }
原来如此。
这就能解释为什么上面容器不能用了。因为我们定义的拷贝构造函数参数是普通引用,必须是只读引用(放开第6行即可用,或者将7行注释掉)。
总结:
- 引用参数 拷贝构造函数用const修饰,这样比较安全规范
- 一旦定义了拷贝构造函数,编译器就使用该构造函数,即使其定义不正确(好像有点废话)
- 不但const函数能重载,const参数也能重载(6,7行同时起作用)