如何一次将多个值分配给一个结构?
我可以在 struct Foo 的初始化时执行此操作:
I can do this on initialization for a struct Foo:
Foo foo = {bunch, of, things, initialized};
但是,我不能这样做:
Foo foo;
foo = {bunch, of, things, initialized};
那么,两个问题:
- 为什么我不能做后者,前者是一个仅用于初始化的特殊构造函数吗?
我该如何做类似于第二个例子的事情,即在一个结构体已经初始化之后,在一行代码中为它声明一堆变量?我试图避免对具有许多变量的大型结构执行此操作:
- Why can't I do the latter, is the former a special constructor for initialization only?
How can I do something similar to the second example, i.e. declare a bunch of variables for a struct in a single line of code after it's already been initialized? I'm trying to avoid having to do this for large structs with many variables:
Foo foo;
foo.a = 1;
foo.b = 2;
foo.c = 3;
//... ad infinitum
推荐答案
第一个是聚合初始值设定项 - 您可以在此解决方案中阅读这些和标记初始值设定项:
The first is an aggregate initializer - you can read up on those and tagged initializers at this solution:
什么是标记结构初始化语法?
这是一种特殊的初始化语法,在你的结构初始化之后你不能做类似的事情.您可以做的是提供一个成员(或非成员)函数来将您的一系列值作为参数,然后您在成员函数中分配这些参数 - 这将允许您在结构以同样的方式初始化后完成此操作简洁(当然是在您第一次编写函数之后!)
It is a special initialization syntax, and you can't do something similar after initialization of your struct. What you can do is provide a member (or non-member) function to take your series of values as parameters which you then assign within the member function - that would allow you to accomplish this after the structure is initialized in a way that is equally concise (after you've written the function the first time of course!)
相关文章