从 C++ 中的子窗体访问父函数

use*_*447 2 c++ forms parent-child

我已经在 C# 或 PHP 甚至动作脚本中看到了这个问题的几个解决方案,但在 C++ 中却没有。我有一个父窗体,它通过新建子窗体并在其上调用 ShowWindow 来调用子窗体。我现在需要子表单能够调用父表单的(公共)函数之一。

我的第一个想法是在子级构造函数中将父级传递给子级,但由于子级不知道父级是什么,我在子级构造函数定义中收到错误。父级知道子级是什么(我在父级表单的头文件中 #included 子级表单的头文件),但我无法在子级头文件中包含父级的头文件而不发生冲突。

关于在 C++ 中实现这项工作的更好方法或方法有什么想法吗?另外,我正在使用 C++ Builder 2010 仅供参考。

我已经找到了解决方案,并将很快发布。

unk*_*ulu 5

您的问题是交叉依赖:父类和子类需要相互了解。但问题是他们不需要知道太多。解决方案是使用如下的前向声明:

parent.h

#include "child.h"

class Parent {
    Child c;
    Parent() : c( this ) {}
};
Run Code Online (Sandbox Code Playgroud)

child.h

class Parent; // this line is enough for using pointers-to-Parent and references-to-Parent, but is not enough for defining variables of type Parent, or derived types from Parent, or getting sizeof(Parent) etc

class Child {
public:
    Child(Parent* p) : parent( p ) {}

private:
    Parent *parent;
};
Run Code Online (Sandbox Code Playgroud)