初始化结构体数组时遇"unexpected initializer before Mov"等错误求助
结构体数组初始化报错解决方案
错误原因
你在main函数里的数组声明存在语法错误,出错的代码行:
Actor Act[100], Movie Mov[100], Cast casts[100];
C++语法规定,同一条声明语句里只能声明同一类型的变量/数组,不能在逗号分隔后重复写其他结构体类型。编译器会将第一个Actor识别为类型,后续的Movie会被误判为变量名的一部分,从而抛出"unexpected initializer before Mov"和"expected primary-expression before Act"错误。
另外你还漏掉了return 0末尾的分号,这也会导致编译问题。
修正后的代码
#include <iostream> #include <ctime> using namespace std; struct Date { int day; int month; int year; }; Date getCurrentDate(){ Date d; time_t theTime = time(NULL); struct tm *aTime = localtime(&theTime); d.day = aTime->tm_mday; d.month = aTime->tm_mon + 1; // Month is 0 - 11, add 1 to get a jan-dec 1-12 concept d.year = aTime->tm_year + 1900; return d; } struct Actor{ string FName, LName, Location; char Gender; int ID, Age; }; struct Movie{ int ID, Day, Month, Year; string Name, Genre; double Gross; float Rating; char slash1, slash2; }; struct Cast { int ActID; int MovID; string Role; }; int main(){ int numMov, numAct, numCast, userchoice; // 每种结构体数组单独声明 Actor Act[100]; Movie Mov[100]; Cast casts[100]; return 0; // 补上缺失的分号 }
关键修改点
- 将不同结构体类型的数组分开声明,每条声明语句对应一种类型
- 补上
return 0末尾的分号,符合C++语句的语法要求
内容的提问来源于stack exchange,提问作者Kyle Lewis
相关产品推荐
相关产品推荐

