【问题标题】:Request for member '' in '', which is of non-class type请求''中的成员'',它是非类类型
【发布时间】:2019-06-15 19:25:52
【问题描述】:

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

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

错误是:

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[i].history[j]
  • 谨慎使用_t 后缀。它们由 POSIX 保留。如果您正在为 Windows 编写代码,问题不大,但可能会在其他任何地方引起问题。

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


【解决方案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。如果适合的话考虑使用。

【讨论】:

  • 我什至把 [] 放在前面的几行中:谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多