![](/img/trans.png)
[英]'Excess elements in struct initializer' error with C++11 uniform initialization
[英]c++11 struct initialization compilation error
struct SS {int a; int s;};
int main ()
{
vector<SS> v;
v.push_back(SS{1, 2});
}
代碼可以編譯沒有任何錯誤。 但是,在類中初始化結構時,出現編譯錯誤。 誰能解釋一下?
struct SS {int a = 0; int s = 2;};
錯誤:
In function ‘int main()’:
error: no matching function for call to ‘SS::SS(<brace-enclosed initializer list>)’
v.push_back(SS{1, 2});
^
note: candidates are:
note: constexpr SS::SS()
struct SS {int a = 0; int s = 2;};
^
note: candidate expects 0 arguments, 2 provided
note: constexpr SS::SS(const SS&)
note: candidate expects 1 argument, 2 provided
note: constexpr SS::SS(SS&&)
note: candidate expects 1 argument, 2 provided
在 C++11 中,當你像這里一樣在聲明點使用非靜態數據成員初始化時:
struct SS {int a = 0; int s = 2;};
你讓班級成為非聚合。 這意味着您不能再像這樣初始化實例:
SS s{1,2};
要使此初始化語法適用於非聚合,您必須添加一個兩個參數的構造函數:
struct SS
{
SS(int a, int s) : a(a), s(s) {}
int a = 0;
int s = 2;
};
此限制已在 C++14 中取消。
請注意,您可能希望為該類添加一個默認構造函數。 用戶提供的構造函數的存在禁止編譯器生成默認構造函數。
請參閱此處的相關閱讀。
使用默認成員初始值設定項將類/結構呈現為非聚合:
§ 8.5.1 聚合
聚合是一個數組或類(第 9 條),沒有用戶提供的構造函數(12.1),沒有用於非靜態數據成員的大括號或等號初始化器(9.2),沒有私有或受保護的非靜態數據成員(第 11 條),沒有基類(第 10 條),也沒有虛函數(10.3)。
聚合和非聚合的語義不同:
聚合(例如,數組和結構):
Initialize members/elements beginning-to-end.
非聚合:
Invoke a constructor.
v.push_back(SS{1, 2}); // Error, it tries to call SS constructor
這意味着您現在需要一個構造函數:
struct SS
{
SS(int a, int s) : a(a), s(s)
{
}
int a = 0;
int s = 2;
};
我有同樣的問題。 在我的例子中,我有兩個struct
,它們都有一些構造函數,包括復制構造函數,從抽象父繼承。
當上面的建議沒有幫助時,我終於意識到我需要從復制構造函數中刪除explicit
說明符並刪除錯誤。
我想我會分享,以防另一個可憐的靈魂像我剛剛做的那樣花很長時間發現這個錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.