how to assign multiple values into a struct at once?(如何一次将多个值分配给一个结构?)
问题描述
我可以在 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!)
这篇关于如何一次将多个值分配给一个结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何一次将多个值分配给一个结构?
基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01