有没有什么方法可以按照与声明顺序不同的顺序指定参数?
例如,假设我有以下结构:
struct Coord
{
int x, y;
};
我可以将它初始化为
auto a = Coord{ y(5),x(4) };
请注意,我问这个问题是出于好奇,我真的不需要做这样的事情。但是我想知道我是否可以在不声明构造函数但指定参数的情况下初始化结构。
最佳答案
很遗憾,您无法更改结构成员构造的顺序。使用 C++20,您可以按名称指定成员(参见 designated initializers )。不幸的是,初始化的名称必须与成员的顺序相同。
这是来自 cppreference(上面的链接)的引述:
Note: out-of-order designated initialization, nested designated initialization, mixing of designated initializers and regular initializers, and designated initialization of arrays are all supported in the C programming language, but are not allowed in C++.
struct Coord
{
int x, y;
};
初始化:
auto a = Coord{ .x=4, .y = 5}; // Ok with C++20
但这行不通(见上面的引述):
auto a = Coord{ .y=5, .x = 4}; // ERROR
对于不同的顺序,您必须定义构造函数或辅助函数。
试试看 compiler explorer .
关于c++ - 具有不同参数顺序的聚合初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55323127/