[英]C++ - member variable aggregate initialization
In the following code: 在下面的代码中:
class Class
{
private:
LUID luid;
public:
Class()
{
luid = { 0, 0}; // A. Does not compile
LUID test = {0, 0}; // B. Compiles
test = {1,1}; // C. Does not compile
}
Why are A and C not right, but B is fine? 为什么A和C不正确,但是B可以呢?
The error I get for A and C is: 我得到的A和C错误是:
error C2059: syntax error : '{' 错误C2059:语法错误:“ {”
error C2143: syntax error : missing ';' 错误C2143:语法错误:缺少';' before '{' 在“ {”之前
error C2143: syntax error : missing ';' 错误C2143:语法错误:缺少';' before '}' 在“}”之前
I think it has to do with the C++ version, although I am not sure which version this is using besides it not being very new. 我认为这与C ++版本有关,尽管除了不太新以外,我不确定它使用的是哪个版本。
Statement LUID test = {0, 0}
is an initialization of a local variable using an initialization list; 语句LUID test = {0, 0}
是使用初始化列表的局部变量的初始化 ; this is valid, as it is used in the course of a variable definition. 这是有效的,因为它在变量定义过程中使用。 test = {0, 0}
, in contrast, is an assignment , as test
is defined elsewhere. 相反, test = {0, 0}
是一个赋值 ,因为test
在其他地方定义。 Assigning initializer lists is supported only in particular cases (eg when assigning to a scalar or to a particular sort of class type (cf., for example, braced-init-list assignment ). 仅在特定情况下(例如,在分配给标量或特定种类的类类型时(例如,参见braced-init-list分配 )),才支持分配初始化器列表 。
Other cases, like, for example, arrays, cannot be assigned but just initialized: 其他情况(例如数组)不能分配,而只能初始化:
typedef int LUID[2];
int main(){
LUID t = { 10, 20 }; // compiles
// t = { 10, 20}; // does not compile, since an array is not assignable
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.