Reputation: 1101
I'm trying to add an object to a vector, but it's not working.
class GameClass{
public:
void makeNewPlayer(int isItBad){
if (isItBad==0){
goodPlayers.push_back(PlayerClass());
}
}
private:
vector<PlayerClass> badPlayers;
vector<PlayerClass> goodPlayers;
};
class PlayerClass{
public:
PlayerClass(int badStatus){
myLocation[0]=rand()%(N-2)+1;
myLocation[1]=rand()%(N-2)+1;
isBad=badStatus;
}
void setMyLocation(int x, int y){
myLocation[0]=x;
myLocation[1]=y;
}
void getMyLocation(int *targetLoc){
targetLoc[0]=myLocation[0];
targetLoc[1]=myLocation[1];
}
private:
int myLocation[2];
int isBad=1;
};
no matching function for call to 'PlayerClass::PlayerClass()'|
goodPlayers.push_back(PlayerClass());
edit: how can i make it default constructor???
Upvotes: 0
Views: 72
Reputation: 29064
You get that error because you do not have a default constructor.. You have a custom constructor hence the default constructor is not automatically supplied.
So you need to pass a value for badstatus something like:
goodPlayers.push_back(PlayerClass(4));
You can make default by making the badstatus as default argument, example:
PlayerClass(int badStatus=4){
myLocation[0]=rand()%(N-2)+1;
myLocation[1]=rand()%(N-2)+1;
isBad=badStatus;
}
Now even if you don't supply the argument of 4, it will work fine.. Give the badstatus a default value.
Suggestion: Always ensure that the default constructor is there for the class. Even if you forgot to pass in the argument, you can still instantiate the object from the class.
In your case, instead of setting int isBad=1; change to int isBad; and add the "=1" to
PlayerClass(int badStatus=1){
myLocation[0]=rand()%(N-2)+1;
myLocation[1]=rand()%(N-2)+1;
isBad=badStatus;
}
Upvotes: 3