![](/img/trans.png)
[英]expected constructor, destructor, or type conversion before ‘*’ token
[英]Error: expected constructor, destructor, or type conversion before ';' token?
我正在尝试编译我的代码来测试一个函数来读取和打印数据文件,但是我得到了一个我不理解的编译错误 - “错误:预期的构造函数,析构函数或类型转换之前';' 令牌”。 相关代码文字的墙壁如下。
struct Day
{
int DayNum;
int TempMax;
int TempMin;
double Precip;
int TempRange;
};
struct Month
{
Day Days[31];
int MonthMaxTemp;
int MonthMinTemp;
double TotalPrecip;
int MonthMaxTempRange;
int MonthMinTempRange;
double AverageMaxTemp;
double AverageMinTemp;
int RainyDays;
double AveragePrecip;
}theMonth;
double GetMonth();
double GetMonth()
{
for (int Today = 1; Today < 31; Today++)
{
cout << theMonth.Days[Today].TempMax << theMonth.Days[Today].TempMin;
cout << theMonth.Days[Today].Precip;
}
return 0;
}
GetMonth(); // compile error reported here
带错误的行看起来像是在试图调用GetMonth - 但在全局层面,C ++程序包含一系列声明。 由于函数调用不是声明,因此它不能在全局级别独立存在。 您可以拥有一个也是定义的声明,在这种情况下,它可以作为初始化的一部分调用函数。
但是,函数调用本身必须包含在其他函数中:
#ifdef TEST
int main() {
GetMonth();
}
#endif
(除了其他回复。)为了执行你的'GetMonth()'函数,你必须从另一个函数('main'或从'main'调用的任何函数)调用它,或者在对象的初始化表达式中使用它在命名空间范围内声明,如
double global_dummy = GetMonth();
但是,后一种方法可能会遇到初始化顺序问题,这就是为什么建议尽可能使用前一种方法。
在C / C ++中,您不能简单地将可执行代码添加到标头或实现(.c,.cpp,.cxx等)文件的主体中。 相反,您必须将其添加到函数中。 如果要在启动时运行代码,请确保将其添加到main方法。
int main(int argc, char *argv[]) {
GetMonth();
}
C ++程序不在全局上下文中执行。 这意味着您需要将对GetMonth的调用放入一个函数中才能运行。 int main() { }
可能是合适的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.