所以,我有幾個類,其中兩個需要相互參考。我用 中的前向宣告解決了回圈參考Entity.h,只是包含Entity.h在我的Timeline.h類宣告中。Entity 有一個子類Human,它希望呼叫Timelineis的方法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;
};
物體.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()到物體,它就會完全失敗。有什么建議?
uj5u.com熱心網友回復:
前向宣告僅在您有指標成員時才有效,但實際上并沒有嘗試取消參考它。
從你的代碼結構來看,如果 Human 是 Entity 的子類,那么在 Human.cpp 的源代碼中,你解參考指向 Timeline 的指標,你需要實際包含 Timeline.h(而不是它的 fw 宣告)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/346326.html
上一篇:二維陣列指標
下一篇:在C中使用指標存盤給定數量的數字
