gpt4 book ai didi

c++ - 调用自动构造函数 : why is my type incomplete?

转载 作者:太空狗 更新时间:2023-10-29 21:32:29 24 4
gpt4 key购买 nike

在下面的代码中,我想使用默认构造函数{.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处理?

最佳答案

您不能聚合初始化私有(private)成员。

来自 https://en.cppreference.com/w/cpp/language/aggregate_initialization

An aggregate is one of the following types: ... class type (typically, struct or union), that has no private or protected non-static data members

由于 a 是一个 class,而不是 structdataprivate.

data 声明为 public,或将类型声明为 struct 以默认为 public .

然后替换 static inline a create(char c) { return {.data = c}; }

with static inline a create(char c) { return a { c }; }

根据 https://en.cppreference.com/w/cpp/language/list_initialization

直接列表初始化(二)

关于c++ - 调用自动构造函数 : why is my type incomplete?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55138528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com