不规范的构造函数与STL容器冲突

来源:互联网 发布:microsoft fix it官网 编辑:程序博客网 时间:2024/04/30 08:07

昨天写代码时用了容器 vector,map.其中元素是自己定义的。比如:


  1. class test
  2. {  
  3. public:
  4. test(){a = 0;b= 0;}

  5. //test(const test& other){a = other.a;b = other.b;} 
  6. test(test& other){a = other.a;b = other.b;}
  7. test& operator=(const test& other){a = other.a;b = other.b;return *this; }
  8. ~test(){}

  9. int a;
  10. int b;
  11. };

 

 

 

 

 

 

 

容器无法push_back()/insert()

 

报错类似于"An object or reference of type "test" cannot be initialized with an expression of type "const test""..

 

原来

  1. void vector<_Ty, _Ax>::insert(iterator _P, size_type _M, const _Ty& _X)
  2.           {_Ty _Tx = _X;
  3. ......
  4.   }

 

 

原来如此。

 

这就能解释为什么上面容器不能用了。因为我们定义的拷贝构造函数参数是普通引用,必须是只读引用(放开第6行即可用,或者将7行注释掉)。

 

总结:

 

  • 引用参数 拷贝构造函数用const修饰,这样比较安全规范
  • 一旦定义了拷贝构造函数,编译器就使用该构造函数,即使其定义不正确(好像有点废话)
  • 不但const函数能重载,const参数也能重载(6,7行同时起作用)