[英]Initialize all struct members
This question regards any C++ plain-old data definition in which there is a constructor that takes all data members as parameters and initializes them.这个问题涉及任何 C++ 普通数据定义,其中有一个构造函数将所有数据成员作为参数并初始化它们。 The only reason for this over extended initializer lists is to prevent the error of only specifying part of the structure.
这种过度扩展初始化列表的唯一原因是为了防止仅指定部分结构的错误。
Here is the typical way to write such a struct:这是编写此类结构的典型方法:
struct Struct {
A a;
B b;
C c;
Struct(A a, B b, C c) : a(a) , b(b), c(c) {}
};
It's worth observing that the type of each member is written twice, and the name four times.值得注意的是,每个成员的类型写了两次,名字写了四次。 In practice, this means the code for such structs is rather compressible.
实际上,这意味着此类结构的代码相当可压缩。 Is there a shorter way to write this struct in C++?
有没有更短的方法来用 C++ 编写这个结构?
If your struct doesn't contain any pointer, you can use aggregate initializer in C++11.如果您的结构不包含任何指针,您可以在 C++11 中使用聚合初始值设定项。
#include <iostream>
using namespace std;
struct xxx {
int a, b, c;
};
int main() {
// your code goes here
xxx x{1,2,3};
cout << x.a << x.b << x.c;
return 0;
}
Interesting question.有趣的问题。 I don't think there is a shorter way to write it, especially here where most of the names are one letter ;)
我不认为有更短的写法,尤其是在大多数名字都是一个字母的地方;)
In general, C++ type definitions tend to be highly repetitive.通常,C++ 类型定义往往高度重复。 You have to repeat the name of the type for all constructors and the destructor, for instance.
例如,您必须为所有构造函数和析构函数重复类型的名称。 Unfortunately, I think the only solution is to have tools generate the code for you.
不幸的是,我认为唯一的解决方案是让工具为您生成代码。
In some cases, you might find useful to use std::par<A, B>
, or std::tuple<A, B, C>
.在某些情况下,您可能会发现使用
std::par<A, B>
或std::tuple<A, B, C>
很有用。
For example:例如:
std::tuple<A, B, C> t = std::make_tuple(a, b, c);
May be this will work for you better in some cases.在某些情况下,这可能更适合您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.