[英]How can i get a function from a different class to call an object declared in Main?
I am making a tictactoe game and would like the function for a player turn to access objects i declared in main and other functions how could i do that?我正在制作一个 tictactoe 游戏,并希望玩家的函数可以访问我在 main 和其他函数中声明的对象,我该怎么做?
void Player1Turn::player1Turn() {
char num;
cin >> num;
if (num == '1')
{
board[0][0] = { xo1 };
}
For example how could i get board to change the values of gameboard?例如,我怎样才能让棋盘改变游戏棋盘的值?
int main()
{
Setup setup;
Gameboard gameboard;
Player1Turn player1turn;
setup.setup();
gameboard.printBoard();
player1turn.player1Turn();
return 0;
}
If this is not enough code I could provide more如果这还不够代码,我可以提供更多
You could add a reference to the specific Gameboard
as an argument to the player1Turn
member function.您可以添加对特定
Gameboard
的引用作为player1Turn
成员函数的参数。 So, assuming your Gameboard
class has a board[][]
member, it would look something like this:所以,假设你的
Gameboard
类有一个board[][]
成员,它看起来像这样:
void Player1Turn::player1Turn(Gameboard& gb)
{
char num;
cin >> num;
if (num == '1')
{
gb.board[0][0] = { xo1 }; // Exact code will depend on your "Gameboard" definition.
}
}
And your call from main
would be like this:你从
main
调用将是这样的:
int main()
{
Setup setup;
Gameboard gameboard;
Player1Turn player1turn;
setup.setup();
gameboard.printBoard();
player1turn.player1Turn(gameboard); // Argument is the Gameboard to work on.
return 0;
}
There are many other ways to achieve this, though, but I can't really suggest anything more/better without more details of your various classes.不过,还有许多其他方法可以实现这一点,但是如果没有有关各种课程的更多详细信息,我真的无法提出更多/更好的建议。 Another way, as suggested in the comment by Nico Schertler , would be to have the reference to
Gameboard
as a "data" member in the Player1Turn
class and pass the reference in its constructor.另一种方式,如建议由尼科Schertler评论,是有参考
Gameboard
作为一个“数据”成员Player1Turn
类,并通过在其构造参考。
Feel free to ask for further clarification and/or explanation.随时要求进一步澄清和/或解释。
PS: Your use of the three names, "Player1Turn" (for the class), "player1Turn" (for the member function) and "player1turn" (for the specific object in main
) is extremely prone to typing errors! PS:您使用“Player1Turn”(对于类)、“player1Turn”(对于成员函数)和“player1turn”(对于
main
的特定对象)三个名称的使用极易出现打字错误! You should seriously consider a better naming scheme!!你应该认真考虑一个更好的命名方案!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.