在 C++ 中,何時呼叫複製建構函式?


複製建構函式是一種使用此前已建立的同類物件來初始化物件而建立物件的建構函式。複製建構函式用於 −

  • 用一個同類型物件初始化另一個同類型物件。
  • 將一個物件複製為一個函式的引數。
  • 將一個物件複製為一個函式的返回值。

如果沒有在類中定義複製建構函式,編譯器會自行定義一個。如果該類有指標變數,並進行了一些動態記憶體分配,那麼必須有一個複製建構函式。最常見的複製建構函式形式如下 −

classname (const classname &obj) {
   // body of constructor
}

此處,obj 是一個物件的引用,用於初始化另一個物件。

示例程式碼

 即時演示

#include <iostream>
using namespace std;

class Line {
   public:
      int getLength( void );
      Line( int len ); // simple constructor
      Line( const Line &obj); // copy constructor
      ~Line(); // destructor

   private:
      int *ptr;
};

// Member functions definitions including constructor
Line::Line(int len) {
   cout << "Normal constructor allocating ptr" << endl;

   // allocate memory for the pointer;
   ptr = new int;
   *ptr = len;
}

Line::Line(const Line &obj) {
   cout << "Copy constructor allocating ptr." << endl;
   ptr = new int;
   *ptr = *obj.ptr; // copy the value
}

Line::~Line(void) {
   cout << "Freeing memory!" << endl;
   delete ptr;
}

int Line::getLength( void ) {
   return *ptr;
}

void display(Line obj) {
   cout << "Length of line : " << obj.getLength() <<endl;
}

// Main function for the program
int main() {
   Line line(10);
   display(line);
   return 0;
}

輸出

Normal constructor allocating ptr
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!

讓我們看看一個相同示例,但做了一點細微改變,即使用現有同類型物件建立一個新物件 −

示例程式碼

 即時演示

#include <iostream>
using namespace std;

class Line {
   public:
      int getLength( void );
      Line( int len ); // simple constructor
      Line( const Line &obj); // copy constructor
      ~Line(); // destructor

   private:
      int *ptr;
};

// Member functions definitions including constructor
Line::Line(int len) {
   cout << "Normal constructor allocating ptr" << endl;

   // allocate memory for the pointer;
   ptr = new int;
   *ptr = len;
}

Line::Line(const Line &obj) {
   cout << "Copy constructor allocating ptr." << endl;
   ptr = new int;
   *ptr = *obj.ptr; // copy the value
}

Line::~Line(void) {
   cout << "Freeing memory!" << endl;
   delete ptr;
}

int Line::getLength( void ) {
   return *ptr;
}

void display(Line obj) {
   cout << "Length of line : " << obj.getLength() <<endl;
}

// Main function for the program
   int main() {
   Line line1(10);
   Line line2 = line1; // This also calls copy constructor

   display(line1);
   display(line2);
   return 0;
}

輸出

Normal constructor allocating ptr
Copy constructor allocating ptr.
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
Freeing memory!

更新於: 2019-07-30

814 次瀏覽

啟動你的 職業

完成該課程以取得認證

開始學習
廣告
© . All rights reserved.