2017-07-18 73 views
-3
struct structA 
{ 
    StructA(const int a) { ... } ; 
} 

,然後我的主要結構:C++構造不匹配功能

.H

struct MainStruct 
{ 
    MainStruct(int x, int y) ; 
private : 
    int _x ; 
    int _y ; 
    StructA _s ; 

} 

*的.cpp

StructA(int x, int y) : _x(x) , _y(y) 
{ 
    _s = StructA(x) ; 
} 

有什麼不對?

如果我將_s = StructA(x) ;替換爲StructA s = StructA(x) ;,並將其從私人中刪除,則可以正常工作。這是爲什麼?

In constructor .... 
no matching function for call to 'StructA' 
         _y(y) 
+3

在您輸入構造函數的主體之前,所有成員都必須完全構造。 '_s'不能被構造,因爲它沒有在成員初始化列表中用適當的參數指定,並且沒有默認的構造函數。 – user4581301

+1

這是由於這樣的事實,即當您使用參數聲明構造函數時,缺省構造函數將在默認情況下被移除(然後您必須明確聲明它)。 –

回答

1

所有集體成員必須在進入構造函數體之前完全構造。 _s不能被構造,因爲它沒有在member initializer list中用適當的參數指定,並且沒有默認構造函數供編譯器用於自動生成的代碼。

快速修復:如果我和StructA s = StructA(x) ;更換_s = StructA(x) ;使用成員初始化列表

MainStruct(int x, int y) : _x(x) , _y(y), _s(x) 
{ 
} 

,並從私人刪除它,它工作正常。這是爲什麼?

因爲_s現在是一個Automatic variable只有MainStruct構造函數中存在。它不再是一個MainStruct類成員,所以它在進入構造函數體之前不需要被初始化。請注意,雖然編譯時它會使_s對您完全無用,因爲它只在MainStruct構造函數中可見,並且會在構造函數結束時被銷燬。

0
struct structA 
{ 
    StructA(const int a) { ... } ; 
} 

意味着你需要提供一個int給它的構造。

MainStruct不這樣做:

StructA(int x, int y) : _x(x) , _y(y) 
{ //by here we need to default construct the _s but cannot 
    _s = StructA(x) ; 
} 

您可以在初始化器排序是:

StructA(int x, int y) : _x(x) , _y(y), _s(x) 
{ 
             //^--- look 
}