【发布时间】: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