我正在为学校开发一款名为 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
}
}
最佳答案
是你的setChips
函数静态?
a nonstatic member reference must be relative to a specific object
你的错误是因为函数setChips
在 chips
时是静态的不是。
如果你希望你的函数是static
, 你需要制作 chips
也是静态的。此外,在 .cpp 的顶部,您需要定义 unsigned Players::chips;
那么你可以使用 ++chips
在你的里面 Player
类函数。
如果你不需要你的函数是static
, 只需删除 static
从你的功能,你仍然可以使用 ++chips
在你的里面 Player
类功能很好。
关于c++ - 从不同类 C++ 访问数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50979422/