如何解决特定的循环依赖?

时间:2014-09-18 17:23:20

标签: c++ class include dependencies

所以我的问题不是关于代码,而是关于如何做到这一点。 我正在使用GUI,我希望我的按钮知道父母是谁。当然,窗口知道它有哪些按钮。

这会创建一个循环依赖,因为两者都需要能够访问其他方法和属性,至少这是我想要的。

我找到了一个有效的解决方案,但我对此并不满意:

我创建了一个按钮写入的第三个对象,它希望窗口做什么。窗口检查第三个对象是否有命令。

我想问你,如果你知道更好的方法,因为我找不到任何其他方式,这对我有用。

谢谢!

2 个答案:

答案 0 :(得分:1)

我建议创建一个窗口界面。在按钮的构造函数中提供指向窗口界面的后向指针。拥有该按钮的窗口取决于按钮,按钮取决于窗口界面。没有循环依赖。

struct IWindow {
};

struct Button {
 IWindow* window_;
 Button(IWindow* window) : window_(window){}
};

struct WindowWithButton : IWindow {
  Button button_;
  WindowWithButton() : button_(this) {}
};

然后将IWindow实施的虚拟方法添加到WindowWithButton,以便Button可以从WindowWithButton获取所需信息。

答案 1 :(得分:0)

这是一种标准模式:

struct Window; // Forward-declare the parent
struct Button {
    void pingParent(); // Only declare members which need
        // more than superficial knowledge of Window
    Window* parent; // Ok, we know there is a Window, somewhere
};
struct Window {
    unique_ptr<Button> child;
    // Other functions using the button
    void pingpong() {child->pingParent();}
    void ping(){}
};
/*optional inline*/ void Button::pingParent() {
    parent->ping();
}
相关问题