在我的项目中创建对象数组时出现问题:应为不合格id



这个(显然是不完整的)项目的目的只是在我空闲的时候对对象进行一些练习。我在测试项目时遇到了以下错误,我不确定到底是什么问题。

"在'[]令牌Competitor[]listOfCompetitors=新的Competitor[10]之前应为不合格id;">

非常感谢您的帮助。

main.cpp

#include <iostream>
#include <string>
#include competitor.cpp;
using namespace std;
int scoringMethod;
int numberOfCompetitors;
int main(int argc, char** argv){
cout<<"How would tou like to score the competition? (please enter an interger)"<<endl;
cout<< "1. Closest Total Points"<<endl<<"2. Closest Total Points Without Going Over" <<endl<<"3. Closest to team1 Score"<<endl<< "4. Closest to Opponent Score"<<endl<<endl;
cin>>scoringMethod;
cout<<endl<<"How many competitors do you have?"<<endl;
cin>>numberOfCompetitors;
Competitor[] listOfCompetitors = new Competitor[10];
string tempName;
int tempScore1, tempScore2;
for (int i = 0; i<numberOfCompetitors;i++){
cout<<"Name of competitor number "<< i<<"?"<<endl;
cin>>tempName;
cout<<tempName<<"'s prediction for team1's score?"<<endl;
cin>>tempScore1;
cout<<tempName<<"'s prediction for the score of team1's opponent?"<<endl;
cin>>tempScore2;
listOfCompetitors[i] = new Competitor(tempName,tempScore1,tempScore2);
}    
cout <<endl<<"The program has reached the end successfully" << endl;
}

competitor.cpp

#include <iostream>
#include <string>
using namespace std;
class Competitor{
private:
string Name;
int team1Score;
int opponentScore;
public:
Competitor(){
Name = "invalid";
team1Score = opponentScore = 0;
}
Competitor(string nameIn, int inteam1Score, int inOpponentScore){
Name=nameIn;
team1Score=inteam1Score;
opponentScore=inOpponentScore;
}
void printData(){
cout<<this->Name<<"'s guess:"<<endl<<"team1: "<<team1Score<< "     Opponent: "<<opponentScore<<endl;
}
};
Competitor[] listOfCompetitors = new Competitor[10];

这在语法上是不正确的(至少对于C/C++来说),也是您出现错误的原因。如果你想动态分配一个Competitors数组,你可以做

Competitor *listOfCompetitors = new Competitor[10];

并且这将动态地分配10个CCD_ 4的阵列。


代码中的其他几个问题:

  1. 您从{0 ... numberOfCompetitors}开始循环,并在每个回合访问您的listOfCompetitors数组。如果numberOfCompetitors≥10怎么办?如果i≥10,则访问listOfCompetitors[i]将变为UB,或未定义的行为

  2. 如果编译的话,下面的行将导致内存泄漏。

    listOfCompetitors[i]=新的竞争对手(tempName,tempScore1,tempScorec2);

listOfCompetitors[i]的类型是Competitor,但new Competitor(...)将返回Competitor*的类型(指向Competitor的指针)。因此,这里的new不是必需的。这就足够了:

listOfCompetitors[i] = Competitor(tempName, tempScore1, tempScore2);
  1. 您没有删除任何动态分配的内存。每次使用new时,都需要记住使用delete,否则会出现内存泄漏。(这有一些例外,但在大多数C++中没有。)您将希望解除分配listOfCompetitors

因此,在完成使用listOfCompetitors之后(可能在for循环之后),执行

delete []listOfCompetitors;
  1. 不应该编译的#include competitor.cpp;。在包含的非标准库文件名周围使用引号:#include "competitor.cpp"

如注释中所建议的,您可以使用std::vectorstd::arraySTL容器。当涉及到动态阵列时,它们更容易使用,并为您完成所有内存管理。(也因为你用C++11标记了你的问题,STL容器将是一个坚实的工作场所。)

我强烈建议拿起一本C++书来阅读和/或参加在线教程,了解动态分配内存、数组等的基本原理。

最新更新