2

*仅供参考 - 我正在做一个介绍性的 OOP 项目。这似乎是一个基本问题,但我在任何地方都找不到明确的解释。

在调用作为其他对象的私有数据成员的对象的成员函数时,我试图避免包装函数。下面我创建了一个简单的说明来说明我的意思。有一个顶级 Game_Manager 对象,其中包含 2 个 Player 对象,每个 Player 对象都包含一个 Weapon 对象。

Game_Manager 知道玩家的武器何时应该攻击。有什么办法可以避免 Player 中的包装函数?这只是糟糕的设计吗?

class Weapon
{
    public:
        void attack();
};

class Player
{
    public:
        void attack()
        {
            weapon.attack();
        }

    private:
        Weapon weapon;
};

class Game_Manager 
{
    public:
        time_for_first_player_to_attack()
        {
            player_1.attack();
        }

    private:
        Player player_1;
        Player player_2;
};
4

1 回答 1

1

也许

class Player
{
    public:
        Weapon getWeapon() { return weapon; } const;

    private:
        Weapon weapon;
};


class Game_Manager 
{
    public:
        time_for_first_player_to_attack()
        {
            player_1.getWeapon().attack();
        }

    private:
        Player player_1;
        Player player_2;
};
于 2013-11-01T07:23:29.547 回答