我有以下情况:
class GenericObject{
virtual Attribute* getAttribute(){..}
}
class PlaneObject : public GenericObject{
Attribute1* getAttribute()override{..}
}
---------------------------------------- block 1
class Attribute{
virtual GenericObject* getObject(){..}
}
class Attribute1 : public Attribute{
PlaneObject* getObject()override{..}
}
---------------------------------------- block 2
由于我覆盖了 PlaneObject 中的 getAttribute() 方法,将其返回类型从 Attribute* 更改为 Attribute1* ,因此仅当编译器知道 Attribute1 派生自 Attribute 时才允许这样做。
那么我应该把 block2 放在 block1 之前。
但是,由于 Attribute1 类中的重写方法,block2 还需要知道 PlaneObject 是从 GenericObject 派生的,以便进行编译。
我不知道这只是糟糕的设计模式还是什么。 我一直在寻找类似的问题,但没有找到与我面对的完全相同的图片。
最佳答案
没有简单的解决方案。您可以尝试以这种方式打破循环:
// GenericObject.h
class Attribute;
class GenericObject{
virtual Attribute* getAttribute();
};
// Attribute.h
class GenericObject;
class Attribute{
virtual GenericObject* getObject();
};
// PlaneObject.h
#include "GenericObject.h"
class Attribute1;
class PlaneObject : public GenericObject
{
Attribute* getAttribute()override;
Attribute1* getAttributeRealType();
};
// Attribute1.h
#include "Attribute.h"
class PlaneObject;
class Attribute1 : public Attribute{
GenericObject* getObject()override;
PlaneObject* getObjectRealType();
};
// implementation example
// PlaneObject.cpp
#include "PlaneObject.h"
#include "Attrubute1.h"
Attribute* PlaneObject::getAttribute()
{
return getAttributeRealType();
}
Attribute1* PlaneObject::getAttributeRealType()
{
return new Attribute1;
}
// attribute1.cpp
#include "Attribute1.h"
#include "PlaneObject.h"
GenericObject* Attribute1::getObject()
{
return getObjectRealType();
}
PlaneObject* Attribute1::getObjectRealType()
{
return new PlaneObject;
}
关于c++ - 具有覆盖方法的继承类的循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61941448/