如何在 C++ 中實現複製建構函式?
下面我們將看到如何在 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!
廣告