2014-09-28 31 views
0

在創建對象,我們可以隱式或顯式調用構造器到參數的構造函數顯式調用拋出Error

Base obj; 
Base obj = Base(1,2); 

這兩種對象創建方法工作正常,直到我包括代碼拷貝構造函數。 這是代碼片段。

#include<iostream> 
using namespace std; 
class Base { 
    public: 
    Base(int x, int y) {} 
    Base() {} 
    Base(Base& o){} 
    private: 
    int a; 
    int b; 
}; 

int main() { 
    Base obj = Base(10,20); /*This line throws error after including copy Ctor*/ 
    Base obj2 = obj; 
} 

我正在使用Linux g ++編譯器。 錯誤:沒有匹配函數調用'Base :: Base(Base)'

我是否錯過了一些東西。

+0

您是否刪除了相關代碼或者您的拷貝構造函數是否真的不初始化? – 2014-09-28 16:09:39

回答

4

拷貝構造函數應該是以下形式,以實現與Base(10,20)

Base(const Base& o){} 
// ~~~~ notice `const` 

或者臨時對象的創建,您可以使用移動的構造與C++ 11,允許臨時對象

Base(Base &&o){} 
+0

謝謝,我在這裏錯過了const。 – Daemon 2014-09-28 17:27:28

2

你有兩種可能性。要麼改變拷貝構造函數的聲明類似

Base(const Base &o){} 

或者添加一個移動構造函數

Base(Base &&o){} 

例如

#include<iostream> 
using namespace std; 
class Base { 
    public: 
    Base(int x, int y) {} 
    Base() {} 
    Base(Base& o){} 
    Base(Base &&){} 
    private: 
    int a; 
    int b; 
}; 

int main() { 
    Base obj = Base(10,20); /*This line throws error after including copy Ctor*/ 
    Base obj2 = obj; 
} 

與您的代碼的問題是,表達Base(10,20)創建一個臨時對象可以用一個常量引用綁定。

實際上你不需要爲這個簡單的類明確地定義拷貝構造函數。

相關問題