![](/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.