如何在 C++ 中初始化结构数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8534526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to initialize an array of struct in C++?
提问by Alexander Galkin
I have the following struct
in my C++ code (I am using Visual Studio 2010):
我的struct
C++ 代码中有以下内容(我使用的是 Visual Studio 2010):
struct mydata
{
string scientist;
double value;
};
What I would like to do is to be able to initialize them in a quick way, similar to array initialization in C99 or class initialization in C#, something á la:
我想要做的是能够以快速的方式初始化它们,类似于 C99 中的数组初始化或 C# 中的类初始化,一些á la:
mydata data[] = { { scientist = "Archimedes", value = 2.12 },
{ scientist = "Vitruvius", value = 4.49 } } ;
If this is not possible in C++ for an array of structs, can I do it for an array of objects? In other words, the underlying data type for an array isn't that important, it is important that I have an array, not a list, and that I can write initializers this way.
如果这在 C++ 中对于结构数组是不可能的,我可以为对象数组做到这一点吗?换句话说,数组的底层数据类型并不重要,重要的是我有一个数组,而不是一个列表,而且我可以用这种方式编写初始化程序。
回答by Bj?rn Pollex
The syntax in C++ is almost exactly the same (just leave out the named parameters):
C++ 中的语法几乎完全相同(只是省略了命名参数):
mydata data[] = { { "Archimedes", 2.12 },
{ "Vitruvius", 4.49 } } ;
In C++03 this works whenever the array-type is an aggregate. In C++11 this works with any object that has an appropriate constructor.
在 C++03 中,只要 array-type 是agregate 就可以工作。在 C++11 中,这适用于任何具有适当构造函数的对象。