【发布时间】:2013-09-27 21:05:11
【问题描述】:
(我阅读了其他依赖/循环继承问题,但找不到此特定案例的答案)
我有一个父类 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定义了一个接口,它不应该知道哪些类型可能从它继承。不同的类可以处理可用/使用的输入设备的实际实例。您可以通过仔细使用前向声明并拆分类型和实现的定义来使其编译,但您可能需要考虑重新设计
标签: c++ inheritance circular-dependency