• <noscript id="yywya"><kbd id="yywya"></kbd></noscript>
  • 發布時間:2020-09-28 23:05 原文鏈接: C++之拷貝構造函數的淺copy和深copy(二)

    (3)注意:

    在寫程序的時候,定義的類對象初始化時看屬于哪種類型的:

    Test t;//對應無參構造函數
    Test t(1);//對應有參構造函數
    Test t1;
    Test t2=t1;//對應拷貝構造函數

    比如下面我定義的類對象屬于無參構造函數(當然前提是你手寫了其他構造函數,雖然說編譯器會默認提供,但是既然要手寫,那么三種構造函數就在定義類對象的時候按需求來寫),如果只寫了有參數構造函數,那么編譯器就會報錯:

    #include <iostream>
    #include <string>
    class Test{
    private:
      int i;
      int j;
    public:
     Test(int a)
     {
        i = 9;
        j=8;
     }
     Test(const Test& p)
      {
         i = p.i;
         j = p.j;
      }
    };
    int main()

      Test t;
     return 0;

    輸出結果:

    root@txp-virtual-machine:/home/txp# g++ test.cpp
    test.cpp: In function ‘int main()’:
    test.cpp:25:9: error: no matching function for call to ‘Test::Test()’
       Test t;
            ^
    test.cpp:25:9: note: candidates are:
    test.cpp:15:3: note: Test::Test(const Test&)
      Test(const Test& p)
      ^
    test.cpp:15:3: note:   candidate expects 1 argument, 0 provided
    test.cpp:10:3: note: Test::Test(int)
      Test(int a)
      ^
    test.cpp:10:3: note:   candidate expects 1 argument, 0 provided

    4、拷貝構造函數的意義:

    (1)淺拷貝

    拷貝后對象的物理狀態相同

    (2)深拷貝

    拷貝后對象的邏輯狀態相同

    (3)編譯器提供的拷貝構造函數只進行淺拷貝

    代碼版本一:

    #include <stdio.h>
    #include <string>
    class Test{
    private:
      int i;
      int j;
      int *p;
    public:
      int getI()
      {
         return i;
      }
      int getJ()
      {
         return j;
      }
      int *getP()
      {
         return p;
      }
      Test(int a)
      {
         i = 2;
         j = 3;
         p = new int;
         *p = a;
     }
     void free()
     {
       delete p;
     }
    };
    int main()

      Test t1(3);//Test t1 3;
      Test t2 = t1;
     printf("t1.i = %d, t1.j = %d, t1.p = %p", t1.getI(), t1.getJ(), t1.getP());
     printf("t2.i = %d, t2.j = %d, t2.p = %p", t2.getI(), t2.getJ(), t2.getP());
      t1.free();
      t2.free();
     
      return 0;


  • <noscript id="yywya"><kbd id="yywya"></kbd></noscript>
  • 东京热 下载