zoukankan      html  css  js  c++  java
  • 关于C++拷贝构造函数

    当类的对象需要拷贝时,拷贝构造函数将会被调用。以下情况都会调用拷贝构造函数:
    (1)一个对象以值传递的方式传入函数体 
    (2)一个对象以值传递的方式从函数返回 
    (3)一个对象需要通过另外一个对象进行初始化。

    深如果一个类拥有资源,当这个类的对象发生复制过程的时候,资源重新分配,这个过程就是深拷贝,反之,没有重新分配资源,就是浅拷贝。

    如果实行浅拷贝,也就是把对象里的值完全复制给另一个对象,如A=B。这时,如果B中有一个成员变量指针已经申请了内存,那A中的那个成员变量也指向同一块内存。这就出现了问题:当B把内存释放了(如:析构),这时A内的指针就是野指针了,出现运行错误。

     1 //浅拷贝
     2 #include <iostream>
     3 using namespace std;
     4  
     5 class CExample {
     6 private:
     7     int a;
     8 public:
     9     CExample(int b)
    10     { a=b;}
    11      
    12     CExample(const CExample& C)
    13     {
    14         a=C.a;
    15     }
    16     void Show ()
    17     {
    18         cout<<a<<endl;
    19     }
    20 };
    21  
    22 int main()
    23 {
    24     CExample A(100);
    25     CExample B=A;
    26     B.Show ();
    27     return 0;
    28 }
     1 //深拷贝
     2 #include <iostream>
     3 using namespace std;
     4 class CA
     5 {
     6  public:
     7   CA(int b,char* cstr)
     8   {
     9    a=b;
    10    str=new char[b];
    11    strcpy(str,cstr);
    12   }
    13   CA(const CA& C)
    14   {
    15    a=C.a;
    16    str=new char[a]; 
    17    if(str!=0)
    18     strcpy(str,C.str);
    19   }
    20   void Show()
    21   {
    22    cout<<str<<endl;
    23   }
    24   ~CA()
    25   {
    26    delete str;
    27   }
    28  private:
    29   int a;
    30   char *str;
    31 };
    32  
    33 int main()
    34 {
    35  CA A(10,"Hello!");
    36  CA B=A;
    37  B.Show();
    38  return 0;
    39 } 
  • 相关阅读:
    [LeetCode#68] Text Justification
    [LeetCode#227] Basic Calculator II
    [LeetCode#87] Scramble String
    [LeetCode#280] Wiggle Sort
    [LeetCode#272] Closest Binary Search Tree Value II
    [LeetCode#254] Factor Combinations
    [LeetCode#174] Dungeon Game
    python报错集合
    在线画图工具
    xml模块(了解)
  • 原文地址:https://www.cnblogs.com/SnowStark/p/4676084.html
Copyright © 2011-2022 走看看