在c++中从子窗体访问父函数
Accessing parent functions from child form in c++
我在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文件中声明多个东西,但是你完全可以声明类而不定义它们,然后再定义它们。
相关文章:
- 如何在函数外部访问函数中局部变量的值?
- UChildActorComponent的ChildActorClass中的访问函数
- 访问函数变体时"Invalid conversion"错误
- 在将向量作为参数传递给函数后,我无法访问函数中向量的元素
- 在64位DLL中访问函数的错误
- 访问函数中 const char *arr[] 的元素
- 访问函数的调用方类型
- 访问函数中的使用声明:与范围相关的问题
- 通过 -> 语法 c++ 从指针访问函数
- 在函数中使用 const 引用参数访问函数中成员的最佳实践 C++.
- 从另一个文件(C++,QT)访问函数未解析的外部
- 如何从主(C )访问函数中的值
- 访问函数 c++ 中的全局变量
- C++ GoogleTest 使用夹具 - 无法访问函数指针定义
- 在不知道名称的情况下访问函数参数
- C++:直接访问器或类内的访问函数
- 无法从对象访问函数
- 类的2D矢量在访问函数时出错
- 为什么在C++中访问函数时没有对象
- 我无法使用指针数组从main访问函数(在类中)