c++嵌套类访问

c++ nested classes access

本文关键字:访问 嵌套 c++      更新时间:2023-10-16

下面是一个简化的头文件,详细说明了三个类。我希望能够保持指针在我的"游戏"类私人,并允许修改它的介绍。然而,这是行不通的。因为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中的受保护成员。但是正如上面的评论所表明的,你实际上在问什么并不是很清楚。