比较两个对象之间的实例。 C ++

问题描述 投票:3回答:1

我目前正在创建一个设计糟糕的战舰游戏,我已经到了一个地方,我无法弄清楚如何从另一个对象访问一些数据。

我有一个棋盘类,它创建了两个大小为100的数组。我有一个玩家类,它有一个属于他们的两个板的实例(他们的棋盘和敌人棋盘(命中,小姐,空))

我正在做的事情是,弄清楚如何使两个玩家的棋盘同步,但在一个功能内板,内部球员......

我的功能假设是不受欢迎的

 class Board{
    int playerBoard[100];
    int enemyBoard[100];

    int makeMove(Move)
      {
        // compare player1.enemyBoard to player2.playerBoard (THIS ??)
      };

 class Player{
    Board playerBoards;

    void makeMove() // edit, the makeMove() in players, cant have parameters
    {
    playerBoards.makeMove(Move x){...};
    };
 }

 Player player1;
 Player player2;

player1.makeMove(Move x);

但是我如何进入player2,而在player1.boards的功能内...我很困惑,任何帮助将不胜感激。我很抱歉这可能导致任何混乱。

c++ object compare instance
1个回答
2
投票

您可以像以下解决方案一样实施

class Board{
      private:
        int player1Board[100];
        int player2Board[100];
      public:
        int* getPlayerBoard(int playerID){
            if (playerID == 1)
                 return &player1Board;
            else if (playerID == 2)
                 return &player2Board;
            else
                 return nullptr;
        }
        int makeMove(Move,int playerID)
        {
           if(playerID == 1){
              //update player1Board
           }
           elseif (playerID == 2){
              //update player2Board
           }
       };

class Player{
    private:
       Board* playerBoards;
       int playerID;

    public:
       Player(int _playerID, Board* _playerBoards){
          playerID = _playerID;
          playerBoards = _playerBoards;
       }
       void makeMove() // edit, the makeMove() in players, cant have parameters
       {
          playerBoards->makeMove(Move x,playerID){...};
       };        
 }

 Board playerBoards;
 Player player1(1,&playerBoards);
 Player player2(2,&playerBoards);

 player1.makeMove(Move x);

为了进一步改进它,你也可以使用单例模式

© www.soinside.com 2019 - 2024. All rights reserved.