c++ - 请求 ''中的成员 '',非类类型

标签 c++ arrays struct compiler-errors initialization

我正在尝试遍历一个结构数组并将其成员“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/

相关文章:

c++ - "delete this"在构造函数中

c++ - 为什么 (10^(-10)) == -4

c++ - 将用户名和密码发送到 Web 服务器的 HTTP 命令是什么?

c# - 排序数组,使所有正数首先出现

c# - 为什么要将 List 转换为 Array

c++ - 静态数据类型(结构)的组织

c++ - 在opencv中找到物体的凸包?

PHP 比较数据库中的 2 个数组,如果找到任何值,则 checkbox=checked

c - 当 union 位于 c 结构体内部时,sizeof() 将返回什么?

c - 错误: derefrencing pointer to incomplete type