首页 > 代码库 > 深拷贝举例

深拷贝举例

 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 = http://www.mamicode.com/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 = http://www.mamicode.com/new object(initValue);23 }24 25 template<class object>26 ObjectCell<object>::ObjectCell(const ObjectCell &rhs) {27     storeValue = http://www.mamicode.com/new object(*rhs.storeValue);>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 = http://www.mamicode.com/*rhs.storeValue;>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 =http://www.mamicode.com/ 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 }