【问题标题】:Avoiding circular references with forward declarations, but unable to access class members避免使用前向声明进行循环引用,但无法访问类成员
【发布时间】:2021-12-17 11:31:10
【问题描述】:

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

时间线.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();
};

事件.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() 实施到实体,它就会完全失败。有什么建议吗?

【问题讨论】:

  • 而不是 long unsigned int - 只需说 unsigned long 。更短更容易阅读。
  • 显然Human.cpp 没有#include 它应该是什么(Timeline.h),但我们缺少minimal reproducible example 可以肯定。投票结束,直到我们得到一个更完整(最好也更小)的例子。
  • #include Timeline.h in Human.cpp.

标签: c++ class pointers forward-declaration circular-reference


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    相关资源
    最近更新 更多