请求“”中的成员“”(非类类型)

时间:2019-06-15 19:25:52

标签: c++ arrays struct compiler-errors initialization

我正在尝试遍历一个struct数组并将其成员“ history”(一个int数组)初始化为0(无疑,您会得到比单值更好的建议-一次循环,这将是受欢迎的,但这不是问题所在。

不仅我不明白,而且我看不到有关它的多个Internet帖子如何在我的案例中起作用的错误。

错误是:

In function 'int main()':....
|error: request for member 'history' in 'coin', which is of non-class type 'coin_t [10]'|

这是我的代码(来自新项目的真实复制粘贴):

#include <iostream>
using namespace std;

// Hand input parameters
const int coinCount=10;
int weight[coinCount]={11,11,9,10,10,10,10,10,10,10};
const int maxDepth=6;
const int caseCount=360;

// GLOBALS
struct coin_t
{
    float w;
    int history[maxDepth];
    int curDepth;
};

coin_t coin[coinCount];

int main()
{
    int i,j;

    //Initialize coin struct array
    for(i=0;i<coinCount;i++)
    {
        coin[i].w=weight[i];
        coin[i].curDepth=-1;
        for(j=0;j<maxDepth;j++) coin.history[j]=0; // Here's the error
    }
}

1 个答案:

答案 0 :(得分:1)

coin是大小为coin_t的结构coinCount的数组。您需要通过operator[]来访问数组中的相应元素。

coin[i].history[j] = 0;
//  ^^^

如果要将history初始化为零,则可以做得更好

struct coin_t
{
    float w;
    int history[maxDepth]{0};
    //                   ^^^^
    int curDepth;
};

您可以跳过多余的循环

    for (j = 0; j < maxDepth; j++)
        coin[j].history[j] = 0;

话说回来,C ++提供了更好的std::array。如果适合情况,请考虑使用。