考虑以下代码:
struct Color // This struct can't be modified
{
double grey;
double rgb[3];
};
int main()
{
double myRGB[3] = {2, 6, 9};
Color c = {10, myRGB}; // This line doesn't work
return 0;
}
如何在一行中初始化一个Color
对象?
在我的真实案例场景中,Color
结构不能更改(例如,使用 std::array
代替 C 样式数组)。
最佳答案
由于 Color
是一个聚合,您可以使用 aggregate initialization并将数组初始化器直接放在大括号中,如
Color c = {10, {2, 6, 9}};
如果你必须用数组初始化c
,因为它很小,你可以像这样展开它
Color c = {10, {myRGB[0], myRGB[1], myRGB[2]}};
关于c++ - 将包含 C 样式数组的对象初始化为成员变量 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53156499/