我正在为学校开发一款名为LCR的骰子游戏。我终于有了要编译的程序,并制定了游戏程序。我现在停留在从Player类访问main中的数组。特别是Player :: setChips。我可能应该使用指针,但在该领域我很粗鲁,任何输入都可能很棒。该函数调用正常,输出有效,但是我注释掉的行显然不起作用,但给出了我想做什么的想法。谢谢。
这是我来自LCR Game.cpp的代码:
int main()
{
// Display Game Rules
Player::directions();
// Get # of Players
int currentPlayer = 0;
srand((unsigned)time(NULL));
const int numPlayers = setPlayers(); //set number of players
static Player* players = new Player[numPlayers]; //set up array
for (int i = 0; i < numPlayers; i++) //set names and chips for each player
{
cout << endl << "Enter player number " << (i + 1) << "'s name: " << endl;
players[i].setName();
players[i].chips = 3;
}
// start game
cout << endl << "OK Let's play!" << endl;
while (winner == false) {
for (int i = 0; i < numPlayers; i++) {
// check if player has chips. if not ++i and skip turn
if (players[i].chips == 0) {
cout << endl << "Sorry " << players[i].name << " you have no chips, you must skip this turn" << endl;
++i;
}
cout << endl << players[i].name << " You have " << players[i].chips << " chips " << " press enter to roll the dice" << endl;
std::cin.ignore(); //wait for keypress
for (int j = 0; j < players[i].chips || j < 3; j++) { // player rolls dice up to 3 times or max chips
Player::setChips(); // call setChips. roll dice & move chips
cout << players[i].chips;
// check for winner after each diceroll
totalChips = 0; // reset chip counter
for (int k = 0; k < numPlayers; k++) { //add all chips on table
totalChips = totalChips + players[i].chips;
}
// check for winner
if (totalChips - players[i].chips == 0) {
cout << endl << "Congratulations " << players[i].name << " you win " << players[i].chips << " chips!";
winner = true;
return 0;
}
}
}
}
return 0;
}
和Player.cpp中的Player :: setChips副本
void Player::setChips()
{
switch (Dice::rollDice()) // roll the dice
{
case 1:
cout << endl << "You rolled <L> "; // subtract 1 chip from player and add one to left
//--players[i].chips;
//if (i = numPlayers) {
// ++players[1].chips;
// }
break;
case 2:
cout << endl << "You rolled <C> "; // subtract 1 chip from player
//--players[i].chips;
break;
case 3:
cout << endl << "You rolled <R> "; //subrtact 1 chip from player and give to right
//--players[i].chips;
//if (i = 1) {
// ++players[numPlayers].chips;
break;
case 4:
cout << endl << "You rolled <*> ";
break; //do nothing
case 5:
cout << endl << "You rolled <*> ";
break; // do nothing
case 6:
cout << endl << "You rolled <*> ";
break; //do nothing
}
}
答案 0 :(得分:1)
您的setChips
函数是静态的吗?
非静态成员引用必须相对于特定对象
您的错误是因为函数setChips
是静态的,而chips
不是静态的。
如果您希望函数为static
,则还需要使chips
为静态。另外,在.cpp的顶部,您需要定义unsigned Players::chips;
,然后可以在++chips
类函数中使用Player
。
如果您不需要将函数设为static
,只需从函数中删除static
,您仍然可以在++chips
类函数中使用Player
很好。