2015-10-05 112 views
2

我有一個簡單的代碼混亂的局面:C++ 11 POD結構初始化錯誤

struct Item { 
    size_t span{}; 
}; 

int main() { 
    Item item{1}; // error is here 
    return 0; 
} 

在編寫這個我下面的錯誤:

test.cpp: In function ‘int main()’: 
test.cpp:8:13: error: no matching function for call to ‘Item::Item(<brace-enclosed initializer list>)’ 
    Item i{1}; 
      ^
test.cpp:8:13: note: candidates are: 
test.cpp:3:8: note: constexpr Item::Item() 
struct Item { 
     ^
test.cpp:3:8: note: candidate expects 0 arguments, 1 provided 
test.cpp:3:8: note: constexpr Item::Item(const Item&) 
test.cpp:3:8: note: no known conversion for argument 1 from ‘int’ to ‘const Item&’ 
test.cpp:3:8: note: constexpr Item::Item(Item&&) 
test.cpp:3:8: note: no known conversion for argument 1 from ‘int’ to ‘Item&&’ 

爲什麼g++試圖找到一個ctorinitializer list在這種情況下,而不是簡單的C風格的結構對象創建?

如果我從size_t span{}刪除{}它編譯成功。

如果我行更改爲size_t span = 0這也恰好所以它似乎是因爲C++ 11所存在問題的聲明一些初始化。

+0

'Item'不是C++ 11中的一個聚集類型(它是C++ 14中的一個聚合) –

+0

@PiotrSkotnicki謝謝,剛剛發現爲什麼我確實認爲它會好起來的 - 閱讀一本關於c + +14,這就是爲什麼我認爲它也適用於C++ 11。 –

+0

自1985年以來C++還沒有結構。關鍵字'struct'聲明瞭一個_class_。 –

回答

5

usign Item item{1};表示您正在做列表初始化(的item)。列表初始化定義如下:

  • 如果該類型是一個聚合,聚合初始化(你指的是什麼的「C風格的struct對象創建」)發生
  • ...
  • 如果類型是一類,構造函數被認爲是

你的類沒有構造函數。它也不是(C++ 11)聚合,因爲它包含非靜態數據成員的初始化程序。

請注意,此限制(成員initialisers)被解除在C++ 14,所以Item一個C++ 14骨料和你的代碼,而不是有效的C++ 11,是有效的C++ 14。