我正在研究一个简单的骰子游戏项目,该项目需要我实例化一个自定义类的多个副本。
vector <Player> playerList;
playerList.resize(totalNumPlayers); //totalNum is grabbed from cin
for (int x = 0; x < totalNumPlayers; x++)
{
playerList.at(x).setname("Player" + to_string(x + 1));
//playerList[x] = p;
playerList.at(x).printName();
cout << playerList[0].returnName() << " " << playerList[1].returnName() << " " << playerList[2].returnName() << endl;
}
玩家职业:
//Declarations
string playerName;
int playerChips;
Player::Player()
{
//Default constructor for when player is created
playerChips = 3;
playerName = "DEFAULT_PLAYER_NAME";
}
void Player::setname(string var)
{
playerName = var;
}
string Player::returnName()
{
return(playerName);
}
void Player::printName()
{
cout << playerName << endl;
}
void Player::addChips(int x)
{
playerChips += x;
}
void Player::removeChips(int x)
{
playerChips -= x;
}
int Player::returnChips()
{
return(playerChips);
}
我注意到,在原始forloop期间的每次迭代中,playerList [x]值始终相同。例如,如果totalNumPlayers = 3,则playerList [0],playerList [1]和playerList [2]都受setName行的影响。因此,当我对PL 1,2和3使用cout时,它总是打印
玩家1,玩家1,玩家1 然后 播放器2,播放器2,播放器2
为什么对每个索引的引用对于它们自己的对象不是唯一的?
答案 0 :(得分:1)
原因很简单。您已经在全局名称空间中定义了string playerName;
(尚未提供源文件的完整结构),因此,每当调用Player::setname
时,都将修改此全局变量,从而在调用时Player::printName()
在for循环中,您只需读取在Player
的所有实例之间共享的变量。要解决此问题,请将此变量移至Player
类中:
class Player
{
private:
string playerName;
public:
Player();
void setname(string var);
string returnName();
string Player::returnName();
void printName();
void addChips(int x);
void printName();
// and the rest of your declarations
};