C ++循环依赖和继承

时间:2013-09-27 21:05:11

标签: c++ inheritance circular-dependency

(我读了其​​他的依赖/循环继承问题,但找不到这个具体案例的答案)

我有一个父类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还是反过来?我也尝试了前向声明类,但这似乎也没有用。

3 个答案:

答案 0 :(得分:1)

这不是循环依赖问题。您只需要在InputDevice.hInputDevice1.h中引用Parent类。

#include "InputDevice.h"放在两个子类中。父类不需要知道它的孩子。

答案 1 :(得分:1)

我认为最简单的答案是将您的抽象类 - InputDevice与其所有访问器和函数 - 从您正在显示的工厂功能中分离出来,即在另一个名为{{1}的文件中创建另一个类},并将InputDeviceFactory放入其中。

然后两个特定的实例将包含InputDevice.h,工厂将包含InputDevice1.h和InputDevice2.h,只需转发声明InputDevice类,InputDevice.h将包含InputDeviceFactory.h。

实际上,InputDevice.h不应该包含InputDeviceFactory。需要工厂的实现应该在.cpp中,而不是.h。这也可以让你在工厂中包含InputDevice.h,而无需进行前向声明。这让我想到了一些不请自来的建议: 尽量避免在.h文件中放置实现(例如GetDevice)。如果你只在.h文件中放入声明,你可以在任何地方包含.h文件,除非存在真正的循环依赖,否则不要担心前向引用。

答案 2 :(得分:1)

您无法在InputDevice::GetDevice定义 InputDevice,因为Device2Device2::IsConnected)的定义尚未见过。所以删除InputDevice::GetDevice的实现  在#include所有三个标题之后将其放入源文件中。

相关问题