繁体   English   中英

从另一个类调用另一个类的函数

[英]Calling a function of another class from another class

我正在一个有两个玩家对象和一个游戏对象的项目中工作。

这两个玩家对象需要访问游戏对象的函数display() ,但是我不知道该怎么做。

以下是突出显示核心问题的摘要:

class Game 
{
public:
    Game() {}
    display() {...}
    ...
};

class Player 
{
public:
    Player() {}
    void input()
    {
        ...
        // display();
        ...
    }
};

请提出解决此问题的方法。 如果您发现此设计模式有根本问题,请随时纠正!

为什么不?

void input()
{
    game.Display();
}

但可能需要将Player对象传递给它。 因此,以这种方式更改它:

class Player; // FORWARD declaration
class Game 
{
public:
    Game() {}
    void display(Player& player); // Implement elsewhere not here.

    // Another way
    void display(Player* player = NULL); // Implement elsewhere not here.
    ...
};
...
 void input()
    {
        game.Display(*this);
           game.Display(this); // another way
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM