[英]Calling automatic constructor: why is my type incomplete?
在下面的代碼中,我想使用默認構造函數{.data = value}
,因為我希望我的類是POD。 我不明白我在編譯時遇到的錯誤信息(llvm或gnu,c ++ 11):
#include <type_traits>
class a {
char data;
static inline a create(char c) { return {.data = c}; } // this fails
static inline a create2(char c) { a x; x.data = c; return x; } // this is OK
public:
void init(char c) { *this = create(c); }
};
int main() {
a s;
s.init('x');
return std::is_pod<a>::value;
}
有錯誤消息
t.cc:5:43: error: no matching constructor for initialization of 'a'
static inline a create(char c) { return {.data = c}; }
^~~~~~~~~~~
t.cc:3:7: note: candidate constructor (the implicit copy constructor) not viable: cannot convert
argument of incomplete type 'void' to 'const a &'
有些靈魂可以向我解釋為什么當我想使用它時,a的類型是不完整的,為什么它被視為void
?
您無法聚合初始化私有成員。
來自https://en.cppreference.com/w/cpp/language/aggregate_initialization
聚合是以下類型之一:...類類型(通常是struct或union),沒有私有或受保護的非靜態數據成員
由於a
是class
,而不是struct
,因此data
是private
。
將data
聲明為public
data
,或將類型聲明為struct
以將其默認為public
。
然后將static inline a create(char c) { return {.data = c}; }
替換static inline a create(char c) { return {.data = c}; }
static inline a create(char c) { return {.data = c}; }
with static inline a create(char c) { return a { c }; }
static inline a create(char c) { return a { c }; }
根據https://en.cppreference.com/w/cpp/language/list_initialization
直接列表初始化(2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.