开发者

Accessing parent functions from child form in c++

I have seen 开发者_如何转开发a couple of solutions to this problem in c# or PHP or even action script, but not in c++. I have a parent form which calls a child form by newing it and calling ShowWindow on it. I now need the child form to be able to call one of the parent form's (public) functions.

My first thought was to pass the parent to the child in the child's constructor, but as the child does not know what the parent is I get an error in my child's constructor definition. The parent knows what the child is (I #included the child form's header file in the parent form's header file), but I can't include the parent's header file in the child's header file without conflict.

Any ideas on better ways or ways to make this work in c++? Also, I am using C++ Builder 2010 fyi.

I have found the solution to this and will be posting it shortly.


Your problem is that of cross-dependency: parent and child classes need to know about each other. But the thing is that they don't need to know too much. A solution is to use a forward declaration like this:

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?

This is because LabelFrm is declared as a pointer. You should either declare it as a member (I'm not sure right now whether this is correct in VCL), or initialize the pointer using syntax like LabelFrm = new TForm1(this, "", this) in the appropriate place (read VCL docs for this, where should the child windows be initialized.

Actually, I get it now, they're not even in parent-child relationship as windows, you can initialize in constructor.


It appears that the best way to do this is as follows:

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;
    }

You shouldn't get any conflicts with multiple things being declared in the .h files but you are perfectly able to declare classes without defining them and just define them later.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜