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 yiibaier; 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 yiibaier; 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!