日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

条款12:复制对象时勿忘其每一个部分

發(fā)布時(shí)間:2025/3/15 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 条款12:复制对象时勿忘其每一个部分 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

設(shè)計(jì)良好的面向?qū)ο笙到y(tǒng)會將對象的內(nèi)部封裝起來,只留兩個(gè)函數(shù)負(fù)責(zé)對象拷貝,即copy構(gòu)造函數(shù)與copy assignment操作符。編譯器會在必要的時(shí)候?yàn)轭悇?chuàng)建coping函數(shù),并說明這些“編譯器生成版”的行為:將被拷貝對象的所有成員變量都做一份拷貝。

任何時(shí)候,只要自己實(shí)現(xiàn)派生類的copying函數(shù),則必須很小心的復(fù)制其基類成分。這些成分往往是private私有的,故無法直接訪問它們,因此應(yīng)該讓派送類的coping函數(shù)調(diào)用相應(yīng)的基類函數(shù):

?void logCall(const string& funcName);
class Customer{public:
     ...Customer(const Customer& rhs);Customer& operator=(const Customer& rhs);
     ...private:string name;Date lastTranscation;};

  

class PriorityCustomer : public Customer{public:...PriorityCustomer(const PriorityCustomer& rhs);PriorityCustomer& operator=(const PriorityCustomer& rhs);...private:int priority;};PriorityCustomer ::PriorityCustomer (const PriorityCustomer& rhs) : Customer(rhs), //調(diào)用基類的copy構(gòu)造函數(shù)priority(rhs.priority){logCall("PriorityCustomer copy constructor");}PriorityCustomer& PriorityCustomer ::operator = (const PriorityCustomer& rhs) {logCall("PriorityCustomer copy assignment constructor");Customer::operator=(rhs); //對基類Customer成分進(jìn)行復(fù)制動作priority = rhs.priority;return *this;}

當(dāng)編寫一個(gè)copying函數(shù),確保1、復(fù)制所有l(wèi)ocal成員變量,2、調(diào)用所有基類的適當(dāng)?shù)腸opying函數(shù)。

注意兩個(gè)錯(cuò)誤用法:1、令copy assignment操作符調(diào)用copy構(gòu)造函數(shù)是錯(cuò)誤的,因?yàn)樵谶@就像試圖構(gòu)造一個(gè)已存在的對象。

         2、令copy構(gòu)造函數(shù)調(diào)用copy assignment操作符同樣是錯(cuò)誤的。構(gòu)造函數(shù)用來出事后對象,而assignment操作符只實(shí)行與已初始化的對象身上。對一個(gè)尚未構(gòu)造好的對象賦值,就像在一個(gè)尚未初始化的對象身上做“z只對已初始化對象才有意義”的事意義。

消除copy構(gòu)造函數(shù)與copy assignment操作符重復(fù)代碼的做法是:建立一個(gè)新的成員函數(shù)給兩者調(diào)用。這樣的函數(shù)往往是private而且被命名為init。這個(gè)策略可以安全消除copy構(gòu)造函數(shù)與copy assignment操作符之間的代碼重復(fù)。

請牢記:

  1、copying 函數(shù)應(yīng)該確保復(fù)制“對象內(nèi)的所有成員變量”及“所有基類成分”。

  2、不要嘗試以某個(gè)copying函數(shù)實(shí)現(xiàn)另一個(gè)copying函數(shù)。應(yīng)該將共同機(jī)能放進(jìn)第三個(gè)函數(shù)中,并由兩個(gè)copying函數(shù)共同調(diào)用。

轉(zhuǎn)載于:https://www.cnblogs.com/lwenwen/p/3468569.html

總結(jié)

以上是生活随笔為你收集整理的条款12:复制对象时勿忘其每一个部分的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。