深拷貝舉例

來源:互聯網
上載者:User

標籤:style   blog   color   os   io   re   

 1 //DeepCopy.cpp  2 #include <iostream> 3 using namespace std; 4  5 template<class object> 6 class ObjectCell { 7     public: 8         explicit ObjectCell(object initValue = object()); 9         ObjectCell(const ObjectCell &rhs);10         ~ObjectCell();11         12         const ObjectCell& operator=(const ObjectCell &rhs);13         14         object read();15         void write(object x);16     private:17         object* storeValue;18 };19 20 template<class object>21 ObjectCell<object>::ObjectCell(object initValue) {22     storeValue = new object(initValue);23 }24 25 template<class object>26 ObjectCell<object>::ObjectCell(const ObjectCell &rhs) {27     storeValue = new object(*rhs.storeValue);28 }29 30 template<class object>31 ObjectCell<object>::~ObjectCell() {32     delete storeValue;33 }34 35 template<class object>36 const ObjectCell<object>& ObjectCell<object>::operator=(const ObjectCell &rhs) {37     if(this != &rhs)38         *storeValue = *rhs.storeValue;39     return *this;40 }41 42 template<class object>43 object ObjectCell<object>::read() {44     return *storeValue;45 }46 47 template<class object>48 void ObjectCell<object>::write(object x) {49     *storeValue = x;50 }51 52 int main() {53     ObjectCell<int> icell1;54     ObjectCell<int> icell2(2);55     ObjectCell<int> icell3(icell2);56 57     cout << icell1.read() << endl;58     cout << icell2.read() << endl;59     cout << icell3.read() << endl;60 61     icell3.write(5);62     cout << icell3.read() << endl;63 64     ObjectCell<int> icell4;65     ObjectCell<int> icell5;66     icell5 = icell4 = icell3;67     cout << icell4.read() << endl;68     cout << icell5.read() << endl;69 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.