在c++中从子窗体访问父函数

Accessing parent functions from child form in c++

本文关键字:访问 函数 窗体 c++      更新时间:2023-10-16

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

我的第一个想法是将父类传递给子类的构造函数,但是由于子类不知道父类是什么,所以我在子类的构造函数定义中得到了一个错误。父窗体知道子窗体是什么(我#将子窗体的头文件包含在父窗体的头文件中),但是我不能将父窗体的头文件包含在子窗体的头文件中而不产生冲突。

有什么更好的方法或方法使它在c++中工作吗?此外,我正在使用c++ Builder 2010供参考。

我已经找到了解决这个问题的方法,并将很快发布。

你的问题是交叉依赖:父类和子类需要相互了解。但问题是,他们不需要知道太多。一个解决方案是像这样使用前向声明:

In parent.h:

#include "child.h"
class Parent {
    Child c;
    Parent() : c( this ) {}
};

In 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;
};
    On the constructor in my parent class is gives the error "Cannot convert from "TEISForm * const" to "TForm1 *" Any ideas?

这是因为LabelFrm被声明为指针。您应该将其声明为成员(我现在不确定这在VCL中是否正确),或者在适当的地方使用像LabelFrm = new TForm1(this, "", this)这样的语法初始化指针(阅读VCL文档,应该在哪里初始化子窗口。

我现在明白了,它们甚至没有父子关系,你可以在构造函数中初始化

最好的方法如下:

Parent.h:

class Child;
class Parent{
public:
Parent(){
//Constructor
}

Parent.cpp:

#include Child.h
//declare a child ie. Child chld = new Child(this);

Child.h:

class Parent;
class Child{
public:
Child(){
//Constructor
}

Child.cpp:

#include Parent.h
Parent prnt;
//point Tell your child that it's parent is of type "Parent" in it's constructor
 Child::Child(TComponent *Owner){
prnt = (Parent *)Owner;
    }

你不应该在。h文件中声明多个东西,但是你完全可以声明类而不定义它们,然后再定义它们。