(我阅读了其他依赖/循环继承问题,但找不到针对此特定案例的答案)
我有一个父类 InputDevice,它将产生两个子类之一。 InputDevice1 是我们期望连接到每台计算机的东西,而 InputDevice2 是可能连接到计算机的东西,我们必须检查它是否是。 InputDevice1 和 InputDevice2 将具有相同的访问器,但内部逻辑却截然不同。
我似乎无法解决依赖性问题 - 解决方案可能是我尚未找到的解决方案,或者我的设计可能很糟糕。
我的 InputDevice.h 看起来像
class InputDevice{
private:
InputDevice* inputDevice;
public:
static InputDevice* GetDevice() {
//we expect only one type of device to be
//connected to the computer at a time.
if (inputDevice == nullptr) {
if (InputDevice2::IsConnected)
inputDevice = new InputDevice2();
else
inputDevice = new InputDevice1();
}
return inputDevice;
}
...standard accessors and functions...
};
而 InputDevice1.h 是:
class InputDevice1 : public InputDevice{
public:
...declarations of any functions InputDevice1 will overload...
}
当 InputDevice2.h 是:
class InputDevice2 : public InputDevice{
public:
static bool IsConnected();
...declarations of any functions InputDevice2 will overload...
}
我不确定在哪些文件中放置#include 语句...InputDevice.h 是引用 InputDevice2.h 还是相反?我也尝试过前向声明类,但这似乎也不起作用。
最佳答案
我认为最简单的答案是将您的抽象类 - InputDevice
及其所有访问器和函数 - 从您正在显示的工厂功能中分离出来,即在另一个名为 InputDeviceFactory
,然后将 GetDevice
放入其中。
那么这两个特定的实例将包含 InputDevice.h,工厂将包含 InputDevice1.h 和 InputDevice2.h,并且只需向前声明 InputDevice 类,InputDevice.h 将包含 InputDeviceFactory.h。
实际上,InputDevice.h 不应该包含 InputDeviceFactory。需要工厂的实现应该在 .cpp 中,而不是 .h 中。这还可以让您在工厂中包含 InputDevice.h,而无需进行前向声明。这给我带来了一些一般性的主动建议:
尽量避免将实现(例如 GetDevice
)放在 .h 文件中。如果您只将声明放在 .h 文件中,则可以在任何地方包含 .h 文件,并且不必担心前向引用,除非存在真正的循环依赖。
关于C++ 循环依赖和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19060058/