在结构类型后定义结构变量 [英] Defining structure variable after structure type
问题描述
#include <iostream>
struct people
{
int id;
} person; // that part
int main()
{
person = {3};
std::cout << person.id;
return 0;
}
我想问您有关初始化结构的问题(嗯,不是初始化。正在创建结构类型...我真的不知道你怎么称呼这个)。我看到了一些结构后面的关键字,例如这里的人。全部没有任何typedef。
I want to ask you about initializing a structure (well, not initialization...creating structure type...I don't really know how do you call this). Once I've seen some keyword after structure, like the "person" here. All without any typedef.
我做了一点研究,发现它用于直接在结构之后定义变量。
I did a little research and found out that it's used to define a variable directly after the structure.
但是,我上面发布的代码无法编译-它表示语法错误,缺少分号和类似的废话,表示该表达式无效。
However, my code I posted above doesn't compile - it says syntax error, missing semicolon and crap like that meaning the expression is not valid.
这是做什么用的,以及如何使用它?
What is this used for, and how to use this?
推荐答案
您不能在常规分配中使用结构初始化语法,它必须是在声明变量时完成:
You can't use the structure initialization syntax in a normal assignment, it has to be done when you declare your variable:
struct people
{
int id;
} person = { 3 };
如果您具有C ++ 11兼容的编译器,则可以使用统一初始化语法,稍后可以复制:
If you have a C++11 compatible compiler, you can use the uniform initialization syntax to copy later though:
person = people { 3 };
这篇关于在结构类型后定义结构变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!