C++ parent 方法访问 child 指针

C++ parent method access to child pointers

我是 C++ 的新手,我正在玩一个类似 roguelike 的小游戏。我有一个名为 Actor 的通用 class,它有 2 个 child class,NPCPlayer。这个想法是让每个 child 包含特定的数据,例如杀死 NPC 或玩家的统计数据所提供的经验,以及特殊的方法。另一方面,Actor包含移动等通用方法,因为玩家和NPC都应该移动。

现在我有一个 vector of NPC pointers,我的移动方法应该检查目标图块是否被 NPC 占用(以及其他一些 NPC 信息),但我无法访问那个 class 来自 Actor。我在 Actor 内向 NPC 添加了前向声明,但随后出现此错误:

pointer to incomplete class type is not allowed

因为前向声明不足以访问 NPC 方法。

Actor.h:

class NPC; // Forward declaration.

class Actor
{
    public:
    void move(std::vector<std::unique_ptr<NPC>> & NPCs);
}

Actor.cpp:

void Actor::move(std::vector<std::unique_ptr<NPC>> & NPCs)
{
    // Go through the NPCs.
    for (const auto &NPC : NPCs)
    {
        if (NPC->getOutlook() > 0) ... // Error.
    }
}

我可以将 move 方法放在 NPCPlayer 中,但我会重复代码,这是一个非常糟糕的主意。

最好的解决方案是什么?我想有更好的方法来组织这个,但它看起来很合乎逻辑。也许某种继承或虚函数魔法?

谢谢! :)

您需要在 Actor.cpp 中包含 NPC 定义的 header,否则 NPC 的定义将丢失。

// Actor.cpp
#include "NPC.h"

void Actor::move(std::vector<std::unique_ptr<NPC>> & NPCs)
{
    // Go through the NPCs.
    for (const auto &NPC : NPCs)
    {
        if (NPC->getOutlook() > 0) ... // Now you'll be able to access this.
    }
}