码迷,mamicode.com
首页 > 其他好文 > 详细

深拷贝举例

时间:2014-07-22 22:52:57      阅读:255      评论:0      收藏:0      [点我收藏+]

标签: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 }

深拷贝举例,布布扣,bubuko.com

深拷贝举例

标签:style   blog   color   os   io   re   

原文地址:http://www.cnblogs.com/dracohan/p/3855324.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!