Effective C++ Item 5 了解 C++ 默默编写并调用哪些函数

来源:互联网 发布:快递单统计软件 编辑:程序博客网 时间:2024/06/06 02:05

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


经验1:

如果你自己没声明,编译器会自动声明copy constructor,copy assignment,destructor,

如果你没有声明任何构造函数,编译器会自动声明default constructor

示例:

如果你写下

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. class Empty{  };  

将会等价于

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. class Empty{  
  2. public:  
  3.     Empty() {...}  //default构造函数  
  4.     Empty(const Empty &rhs) {...} //copy 构造函数  
  5.     ~Empty() {...} //析构函数  
  6.       
  7.     Empty &operator=(const Empty &rhs) { ... } //copy assignment 操作符  
  8. }  

只有当这些函数被调用时,编译器才会创建它们

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Empty e1; //default构造函数, 析构函数  
  2.   
  3. Empty e2(e1); //copy 构造函数  
  4. e2 = e1; //copy assignment操作符  


经验2:如果你打算在一个“内含reference成员”或“内含const成员”的class内支持赋值操作,你必须自己定义copy assignment操作符。因为C++并不允许让reference改

指向不同对象;const成员不可以被修改

示例:如果class“内含reference成员”或“内含const成员”,则编译器不会自动生成copy assignment操作符

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. template<class T>  
  5. class NamedObject  
  6. {  
  7. public:  
  8.     NamedObject(std::string &name, const T &value): nameValue(name), objectValue(value){}  
  9. private:  
  10.     std::string &nameValue; //reference  
  11.     const T objectValue;     //const  
  12. };  
  13.   
  14.   
  15. int main(){  
  16.     string newDog("Persephone");  
  17.     string oldDog("Satch");  
  18.     NamedObject<int> p(newDog, 2);  
  19.     NamedObject<int> s(oldDog, 36);  
  20.     p = s;  
  21.     system("pause");  
  22. }  


输出:

(出错)error C2582: 'operator =' function is unavailable in 'NamedObject<T>'


0 0
原创粉丝点击