请求''中的成员'',非class类型

Request for member '' in '', which is of non-class type

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

我得到一个错误,不仅我不明白,而且我看不出关于它的多个互联网帖子如何在我的案例中发挥作用。

错误是:

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
    }
}

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

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

如果你想 zero-initialize 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。适合情况下考虑使用