证同测试
復制構造函數與復制賦值的區別如下:
class Name {
? ? const char* s;
? ? //...
};
class Table {
? ? Name* p;
? ? size_t sz;
public:
? ? //...
? ? Table(const Table&);? ? //復制構造函數
? ? Table& operator=(const Table&);? ? //復制賦值
};
Table::Table(const Table& t) {? ? /*復制構造函數*/
? ? p=new Name[sz=t.sz];
? ? for(int i=0;i<sz;++i) p[i]=t.p[i];
}
Table& Table::operator=(const Table& t) {? ? /*賦值*/
? ? if(this != &t) {? ? /*當心自賦值:t=t,證同測試*/
? ? ? ? delete[] p;
? ? ? ? p=new Name[sz=t.sz];
? ? ? ? for(int i=0;i<sz;++i) p[i]=t.p[i];
? ? }
? ? return *this;
}
復制構造函數是去完成對未初始化的存儲區的初始化,而復制賦值運算符則必須正確處理一個
結構良好的對象。賦值運算符的一般性策略非常簡單:防止自賦值,刪除那些老元素,初始化,
復制那些新元素。
轉載于:https://www.cnblogs.com/donggongdechen/p/9691175.html
總結
- 上一篇: Ubuntu16.04下使用ufw保护d
- 下一篇: WordCount