使用前向声明避免循环引用,但无法访问 class 成员

Avoiding circular references with forward declarations, but unable to access class members

所以,我有几个 classes,其中两个需要相互引用。我在 Entity.h 中用前向声明解决了循环引用,只是在我的 Timeline.h class 声明中包含了 Entity.h。实体有一个 subclass Human 有望调用 Timeline 中的方法,即 timeline->addEvent(...).

Timeline.h

#include <queue>
#include "Event.h"

class Timeline {
private:
    std::priority_queue<Event> events;
    long unsigned int currentTime = 0;
public:
    Timeline() = default;
    ~Timeline() = default;

    void addEvent(long unsigned int timestamp, EventType type, Entity *entity);
    void processEvent();
    void getCurrentTime();
};

Event.h

#include "Entity.h"

class Event {
private:
    long unsigned int timestamp;
    EventType type;
    Entity *entity;
public:
    Event(long unsigned int timestamp, EventType type, Entity *entity);
    ~Event() = default;
    long unsigned int getTimestamp();
    EventType getType();
    Entity *getEntity();

    bool operator<(const Event &rhs) const;
    bool operator>(const Event &rhs) const;
    bool operator<=(const Event &rhs) const;
    bool operator>=(const Event &rhs) const;
};

Entity.h

class Event;
class Timeline;

class Entity {
protected:
    Timeline *timeline;
    long unsigned int currTimestamp;
public:
    explicit Entity(Timeline *timeline, unsigned int age);
    virtual void processEvent(Event event) = 0;
};

Human.cpp(调用时间线->addEvent(...))

void Human::sleep(Event event) {
    Animal::sleep(event);
    unsigned int timeBlock = 96;
    this->timeline->addEvent(this->currTimestamp + timeBlock, EventType::AWAKEN, this);
}

和错误日志

error: invalid use of incomplete type ‘class Timeline’
     this->timeline->addEvent(this->currTimestamp + timeBlock, EventType::AWAKEN, this);

note: forward declaration of ‘class Timeline’
     class Timeline;

我想我只是对为什么这会成为一个问题感到困惑。当它只是 class Event; 时使用前向声明很好,但是一旦添加 class Timeline; 以将 addEvent() 实现到实体,它就会完全失败。有什么建议吗?

前向声明仅在您有指针成员时才有效,但实际上并没有尝试取消引用它。

从你的代码结构来看,如果 Human 是 Entity 的子类,那么在 Human.cpp 的源代码中你取消引用指向 Timeline 的指针,你需要实际包含 Timeline.h (而不是它的 fw 声明)。