简体   繁体   English

C ++父方法访问子指针

[英]C++ parent method access to child pointers

I'm pretty new to C++ and I am working in a little roguelike game. 我是C ++的新手,并且正在从事类似roguelike的游戏。 I have a generic class named Actor , which has 2 child classes, NPC and Player . 我有一个名为Actor的泛型类,它具有2个子类NPCPlayer The idea is for each child to contain specific data, such as experience provided by killing an NPC or the Player's stats, and special methods. 这个想法是让每个孩子都包含特定的数据,例如杀死NPC或玩家的数据所提供的经验以及特殊的方法。 On the other hand, Actor contains general methods such as move, because both player and NPC should move. 另一方面, Actor包含诸如move之类的常规方法,因为玩家和NPC都应该移动。

Now I have a vector of NPC pointers , and my move method should check if the target tile is occupied by an NPC (and some other NPC info), but I don't have access to that class from Actor . 现在我有了一个vector of NPC pointers ,我的move方法应该检查目标图块是否被NPC占用(以及其他一些NPC信息),但是我无法从Actor访问该类。 I added a forward declaration to NPC inside of Actor , but then I get this error: 我在Actor内向NPC添加了前向声明,但随后出现此错误:

pointer to incomplete class type is not allowed 不允许指向不完整类类型的指针

because forward declaration is not enough to access NPC methods. 因为前向声明不足以访问NPC方法。

Actor.h: Actor.h:

class NPC; // Forward declaration.

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

Actor.cpp: 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.
    }
}

I could put the move method inside both NPC and Player , but I would be duplicating code, and that's a pretty bad idea. 我可以将move方法放入NPCPlayer ,但是我将复制代码,这是一个非常糟糕的主意。

What would be the best solution here? 什么是最好的解决方案? I guess there is a better way to organize this, but it seems pretty logical as it is. 我想有一个更好的方法来组织它,但是看起来很合乎逻辑。 Maybe some kind of inheritance or virtual functions magic? 也许某种继承或虚函数魔术?

Thanks! 谢谢! :) :)

You will need to include the header where NPC is defined in Actor.cpp, otherwise the definition of NPC will be missing. 您需要在Actor.cpp中定义NPC的地方包含标头,否则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.
    }
}

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

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