c++嵌套类访问
c++ nested classes access
下面是一个简化的头文件,详细说明了三个类。我希望能够保持指针在我的"游戏"类私人,并允许修改它的介绍。然而,这是行不通的。因为Introduction是GameState的衍生品,我想我是否可以修改这个指针?实例表明,这是可能的。我真的不想把这个移到Game的公共空间
class Introduction;
class Game;
class GameState;
class GameState
{
public:
static Introduction intro;
virtual ~GameState();
virtual void handleinput(Game& game, int arbitary);
virtual void update(Game& game);
};
class Introduction : public GameState
{
public:
Introduction();
virtual void handleinput(Game& game, int arbitary);
virtual void update(Game& game);
};
class Game
{
public:
Game();
~Game();
virtual void handleinput(int arbitary);
virtual void update();
private:
GameState* state_;
};
我所遵循的例子是在这里…http://gameprogrammingpatterns.com/state.html
编辑:我想做这样的事情…
void Introduction::handleinput(Game& game, int arbitary)
{
if (arbitary == 1)
std::cout << "switching to playing state" << std::endl;
game.state_ = &GameState::play;
}
编辑:谢谢你的回复,我认为getter和setter是正确的方法。我为问题不清楚而道歉。问题是我不理解我试图遵循的实现。我还是不明白,但很明显,有很多方法可以做到同样的事情。
我看到两个可能的解决方案。
使用Friend类
你可以在你的Game
类中声明friend
类。
类似:
class Game {
public:
// ...
private:
// ...
friend class Introduction;
};
这样,Introduction
类就可以访问Game
类的私有成员并对其进行修改。
getter和setter
如果你想保留数据隐藏原则,你可以提供一个public成员来修改你的游戏状态。
这里有一个例子:
class Game {
public:
void setNewState(GameState* setter) noexcept;
const GameState* getCurrentState() const noexcept;
// ...
};
getter和setter呢?
class Game
{
public:
....
GameState * getGameState() const { return state_; }
void setGameState(GameState * newState) { state_ = newState; }
....
private:
GameState* state_;
}
您可以将指针设置为Protected并将Game设置为GameState的好友,以允许Game访问GameState中的受保护成员。但是正如上面的评论所表明的,你实际上在问什么并不是很清楚。
相关文章:
- 无法访问嵌套类.类的使用无效
- C++将结构传递给函数以访问嵌套结构
- 如何访问嵌套类的数据?
- 如何访问嵌套在命名命名空间中的未命名命名空间变量?
- 优雅地访问嵌套类中的数据
- 在 c++ 中访问嵌套字典unordered_map<字符串、void*>?
- 为什么 clang 不允许通过实例访问嵌套枚举类?
- 访问嵌套块中重新定义的变量
- 访问嵌套结构的数据成员并将结构传递到功能C
- 在循环访问嵌套向量时删除元素
- 使用QQMLContext访问嵌套ListView
- 访问嵌套模板类型
- 访问嵌套结构中的数据
- 访问嵌套类中的变量时出现问题
- 访问嵌套类(如果容器没有其实例)
- 为什么我的向量无法访问嵌套结构中的变量?
- 访问嵌套类的成员
- 如何从C++访问嵌套的 QML 对象
- 如何访问嵌套的stl元素
- 访问嵌套的STL结构和大小调用