我正在尝试遍历一个结构数组并将其成员“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;
// ^^^
如果你想对 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
.适合情况下考虑使用。
关于c++ - 请求 ''中的成员 '',非类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56613549/