gpt4 book ai didi

c++ - 使用枚举和结构?

转载 作者:行者123 更新时间:2023-11-28 01:37:18 25 4
gpt4 key购买 nike

我有一个关于在我的家庭作业中使用 enumstruct 的问题,我有点难以理解。

首先,这是老师给我们的代码示例。

enum MonthType {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC};
struct WeatherType
{
int avgHiTemp;
int avgLoTemp;
float actualRain;
float recordRain;
};

家庭作业然后说要声明一个一维数组类型,WeatherListType,由 WeatherType 组件组成,由 MonthType 类型的值索引>。当我尝试通过编码来做到这一点时:

typedef WeatherType WeatherListType[MonthType];

我遇到了这些错误:

problem5.cpp:19:47: error: expected primary-expression before ']' token 
typedef WeatherType WeatherListType[MonthType];
^
problem5.cpp:21:2: error: 'WeatherListType' was not declared in this scope
WeatherListType yearlyWeather;

我只是对问题在问什么感到困惑,如果我在正确的轨道上,我到底做错了什么?

最佳答案

这里的问题是在

typedef WeatherType WeatherListType[MonthType];

方括号 [] 之间的东西必须是一个数字(它是元素的数量)但是 MonthType 不是一个数字,它是一个类型。

这里有两个主要选项:

  1. 只需使用 12。

  2. 添加另一个枚举项:enum MonthType {..., NOV, DEC, NUM_MONTHS};

    然后使用 NUM_MONTHS。

    这是枚举的一个常见技巧 - 因为它们从 0 开始向上计数,NUM_MONTHS 将是第 13 个值,所以它得到值 12。

    这样做的原因是,如果您添加另一个值,编译器会自动为您调整 NUM_MONTHS。我不认为我们很快就会有新的月份,所以在这种情况下没关系。

(旁注:在 C 语言中,数组总是由整数索引。你不能通过枚举来索引一个数组。但是枚举可以转换为整数并返回,所以这不是问题)

关于c++ - 使用枚举和结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48739726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com