zoukankan      html  css  js  c++  java
  • c++-深拷贝

     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 }
  • 相关阅读:
    js使用笔记
    rabbit-mq使用官方文档
    tomcat Enabling JMX Remote
    Venom的简单使用
    Random模块
    时间模块
    shulti模块简述
    Python的os模块
    Python压缩及解压文件
    Kali的内网穿透
  • 原文地址:https://www.cnblogs.com/dracohan/p/3855324.html
Copyright © 2011-2022 走看看