2015-10-23 63 views
2

複製構造函數調用默認構造函數的同時在C++中創建對象?如果我隱藏默認的構造函數,我應該仍然能夠創建副本,對吧?複製構造函數調用默認構造函數以創建對象

+0

目前尚不清楚你在想什麼「默認構造函數」。當你的代碼沒有它們並且你沒有指定一個明確的'delete'時,C++會提供默認的構造函數。然後有無參數的構造函數也被稱爲「默認」,但是你的類不需要具有其中的一個。 – dasblinkenlight

+0

不管我的問題。兩者都是默認的,我不在乎它是編譯器生成的還是程序員定義的。 – Narek

回答

1

刪除默認構造函數並不妨礙您複製對象。當然,您需要一種方法來首先生成對象,即您需要提供一個非默認構造函數。

struct Demo { 
    Demo() = delete; 
    Demo(int _x) : x(_x) { cout << "one-arg constructor" << endl; } 
    int x; 
}; 

int main() { 
    Demo a(5); // Create the original using one-arg constructor 
    Demo b(a); // Make a copy using the default copy constructor 
    return 0; 
} 

Demo 1.

當你寫你自己的拷貝構造函數,你應該將呼叫路由到與參數的適當的構造,就像這樣:

struct Demo { 
    Demo() = delete; 
    Demo(int _x) : x(_x) { cout << "one-arg constructor" << endl; } 
    Demo(const Demo& other) : Demo(other.x) {cout << "copy constructor" << endl; } 
    int x; 
}; 

Demo 2.