首页 > 解决方案 > 为什么我的类不能访问它自己的另一个对象的私有声明变量

问题描述

我收到以下错误

game.cpp:19:35: error: ‘Player Game::p1’ is private within this context
   19 |  Point playerMove = tictactoeGame.p1.makeMove();
      |                                   ^~
In file included from game.cpp:1:
game.hpp:12:10: note: declared private here
   12 |   Player p1;

其次是与其他变量相同情况的 3 个错误。我认为我可以访问这些成员,因为它们是 Game 对象的一部分。

这是我指的我的课

// game.hpp

#ifndef GAME
#define GAME

// Includes
#include "player.hpp"
#include "board.hpp"
  
class Game
{ 
    private:
        Board gameboard;
        Player p1;
        Player p2;
    public:
        Game(Board& gb, Player& p1, Player& p2);
        bool checkWinner(); // Determine if their is a winner or tie, or if the game is still going.
        void announceResults(int winner); // Announce the winner and end the game.
        bool checkMoveValidity(const Point& sector); // Check if the players move is a valid move.
};
  
#endif


//game.cpp

#include "game.hpp"

Game::Game(Board& gb, Player& p1, Player& p2) : gameboard{gb},p1{p1},p2{p2} {}

// Some functions that were implemented

// Main to test out some functions
int main()
{
    Board tictactoeBoard;
    Player x('x',"Caleb");
    Player o('o',"Caleb2");
    Game tictactoeGame(tictactoeBoard, x, o); 

    Point playerMove = tictactoeGame.p1.makeMove(); ///// Error here
    while(true)
    {
        if(tictactoeGame.checkMoveValidity(playerMove))
        {
            tictactoeGame.gameboard.placePiece(playerMove,tictactoeGame.p1); ///// Error here
            break;
        }
        else
        {
            std::cout << "Invalid move. Please enter a valid move.";
            playerMove = tictactoeGame.p1.makeMove(); ///// Error here
        }
    }

}

此外,这里是定义的成员player.hppboard.hpp


//player.hpp
class Player
{
    private:
        char symbol;
        std::string name;
    public:
        //////
}

//board.hpp
class Board
{
    private:
        std::array<std::array<char,3>,3> board;
    public:
        int rows;
        int cols;
}

虽然这些对象也有私有属性,但我认为它们可以在游戏类中访问。

我是否需要Game在这两个课程中结交朋友,或者这会破坏封装?

标签: c++

解决方案


正如评论者所指出的,导致错误的代码行在函数内main,作为一个独立的函数,它不能访问类的私有变量。只有类的方法可以访问私有变量。


推荐阅读