c++ - 为什么我的类不能访问它自己的另一个对象的私有声明变量
问题描述
我收到以下错误
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.hpp
和board.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
在这两个课程中结交朋友,或者这会破坏封装?
解决方案
正如评论者所指出的,导致错误的代码行在函数内main
,作为一个独立的函数,它不能访问类的私有变量。只有类的方法可以访问私有变量。
推荐阅读
- http - 了解 OData 服务
- blockchain - 如何使用 web3 处理 Solidity uint 数组
- javascript - 如何在不调整reactjs中的背景图像大小的情况下进行缩放
- java - 在 openxmlformats 中更改图表的轴颜色和字体
- rx-java - RxJava Scheduler.Worker schedule 订阅 Observable 的操作
- android - 带有 2 个 Fragment 屏幕的 Google play 游戏服务
- php - 当我打电话给她 7.0 时,我的函数的参数很少
- python - Python动态创建xml文件
- python - 如何细分熊猫数据框
- windows - 如何将 %userprofile% 放入 puppet exec