帮助声明C ++结构,将float数组作为其成员之一

时间:2009-03-09 18:41:47

标签: c++ arrays structure declaration

我想知道是否有人能发现我的结构声明和使用有什么问题。目前我有一个结构,并希望将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

3 个答案:

答案 0 :(得分: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};

答案 1 :(得分:3)

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

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]的初始值设定项。加入适当的值。否则会有默认初始化 - 这就是你想要的吗?

答案 2 :(得分:0)

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

浮点数组没有“构造函数”可以复制另一个数组的元素。