简体   繁体   English

C ++结构值初始化

[英]C++ Struct Value Initialization

I was messing around with structs and noticed that of the following two examples, only one worked. 我正在搞乱结构,并注意到以下两个例子,只有一个有效。 Here they are: 他们来了:

struct Test
{ 
    char *name; 
    int age; 
}; 

Test p1 = { "hi", 5 };
//works


struct Test
{ 
    char *name; 
    int age; 
}p1; 

p1 = { "hi", 5 };
//error

How come the first one compiles and the second one doesn't? 为什么第一个编译而第二个编译不? Isn't p1 an object of Test either way? p1不是Test的对象吗? Thanks. 谢谢。

In the first example you are initializing a struct with two values in a "brace initialization." 在第一个示例中,您将在“大括号初始化”中初始化具有两个值的结构。 There is no support in C++ (or C) for assigning to a struct using a brace-enclosed list. C ++(或C)中不支持使用括号括起的列表分配给结构。

You could, however, create a new struct using brace initialization, then assign it to the old struct ( p ). 但是,您可以使用大括号初始化创建一个新结构,然后将其分配给旧结构( p )。 C++ (and C) does support assignment of one struct to another of the same type. C ++(和C)支持将一个结构分配给同一类型的另一个结构。

For example, in C++11: 例如,在C ++ 11中:

p1 = Test{ "hi", 5 };

The following does work with C++11: (Compile with g++ -std=c++11 init.cpp ) 以下适用于C ++ 11 :(使用g++ -std=c++11 init.cpp

#include <iostream>

struct XXX {
    int a;
    const char *b;
};

int main() {
    XXX x;
    x = XXX{1, "abc"};
    // or later...
    x = XXX{2, "def"};

    std::cout << x.b << std::endl;

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM