簡體   English   中英

C ++ 11 POD結構初始化錯誤

[英]C++11 POD structure initializing error

我對簡單的代碼感到困惑:

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++嘗試為initializer list找到ctor而不是創建簡單的C樣式結構對象?

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

如果我將行更改為size_t span = 0 ,也會發生這種情況,因此似乎是自c ++ 11起存在的聲明問題中的一些初始化。

Usign Item item{1}; 表示您正在 (進行item )的列表初始化 列表初始化定義如下:

  • 如果類型是集合,則發生集合初始化(您稱為“ C樣式結構對象創建”)
  • ...
  • 如果類型是類,則考慮構造函數

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

請注意,此限制(成員初始化程序)已在C ++ 14中取消,因此Item C ++ 14的聚合,並且您的代碼(雖然無效的C ++ 11)是有效的C ++ 14。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM