c++ - 具有覆盖方法的继承类的循环依赖

标签 c++ inheritance overriding virtual-functions circular-dependency

我有以下情况:

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/

相关文章:

Java:对象的初始化顺序

java - 覆盖默认外观 Java

c++ - 使用类名的模板值作为指针

c++ - MySQL 连接器问题 - 链接甚至更多

C++,在基类上调用 delete 结果?

java - 我必须使用 instanceof 还是有任何多态解决方案?

c++ - 在 Boost Spirit 中解码字符 UTF8 转义

c++ - 带有准备好的语句的 libpqxx 数组数据

java - 在运行时重写或修改 Java 类构造函数

c++ - 调用虚函数的覆盖导致段错误