我想知道是否有人能发现我的结构声明和使用有什么问题。目前我有一个结构,并希望将float数组存储为其中一个成员。

我的代码:

struct Player{
float x[12];
float y[12];
float red,green,blue;
float r_leg, l_leg;
int poly[3];
bool up,down;
};

然后我尝试填充结构:

float xcords[12] = {1,1,1,1,1,1,1,1,1,1,1,1 };
float ycords[12] = {1,1,1,1,1,1,1,1,1,1,1,1 };
Player player = {xcords,ycords,1,1,1,2,2,true,true};

错误:

1>.\template_with_console.cpp(35) : error C2440: 'initializing' : cannot convert from 'float [12]' to 'float'
1>        There is no context in which this conversion is possible
1>.\template_with_console.cpp(35) : error C2440: 'initializing' : cannot convert from 'float [12]' to 'float'
1>        There is no context in which this conversion is possible
有帮助吗?

解决方案

在大多数情况下,数组衰减到数组的指向第一个元素,就像 xcords ycords 一样。你不能像这样初始化结构。因此,您必须明确初始化成员:

Player player = {
        {1,1,1,1,1,1,1,1,1,1,1,1 }, // xcords
        {1,1,1,1,1,1,1,1,1,1,1,1 }, // ycords
        1,1,1,                      // red, green, blue
        2,2,                        // right, left
        {0,1,2},                    // poly[3]   -- missing?          
        true,true};                 // up, down

如果我理解正确的话,你也缺少poly [3]的初始值设定项。加入适当的值。否则会有默认初始化 - 这就是你想要的吗?

其他提示

尝试

Player player = {{1,1,1,1,1,1,1,1,1,1,1,1 },
                 {1,1,1,1,1,1,1,1,1,1,1,1 },
                 1,1,1,
                 2,2,
                 {},
                 true,true};

我认为你期望初始化将每个数组的元素复制到你的结构中。尝试单独初始化结构中的数组元素,例如使用 for 循环。

没有“构造函数”对于将复制另一个数组的元素的float数组。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top