简体   繁体   English

在C ++中的父级构造函数中调用重写的方法

[英]Call overridden method in parents constructor in C++

I have some code (C++11) like this: 我有一些这样的代码(C ++ 11):

Form.hpp: Form.hpp:

class CForm{
public: 
     CForm(int paTemplate);
protected:
     virtual void createFromTemplate(int paTemplate);
}

Dialog.hpp Dialog.hpp

class CDialog : public CForm {
public:
    CDialog(int paTemplate);
private:
    void createFromTemplate(int paTemplate);
};

Form.cpp 表格

CForm::CForm(int paTemplate){
    createFromTemplate(paTemplate);
}

Dialog.cpp 对话框.cpp

CDialog::CDialog(int paTemplate) : CForm(paTemplate){
    active = false;
}

I want my dialog to call it's own createFromTemplate , in this way the form's createFromTemplate is called. 我希望我的对话框调用它自己的createFromTemplate ,以这种方式调用表单的createFromTemplate How can I achieve it? 我该如何实现? (I call CDialog(template); in my main ). (我在main调用CDialog(template); )。

This is not possible - when you call virtual function in constructor/destructor, the version from "this" class or below is called. 这是不可能的-在构造函数/析构函数中调用虚拟函数时,将调用“ this”类或更低版本中的版本。 In your case, it would always call CForm::createFromTemplate(), no matter what you do. 就您而言,无论您做什么,它将始终调用CForm :: createFromTemplate()。

Check this link - http://www.artima.com/cppsource/nevercall.html - it's a chapter from "Effective C++". 检查此链接-http: //www.artima.com/cppsource/nevercall.html-这是“有效C ++”中的一章。

The problem here is that CDialog is not yet created (remeber class construction order: from top to bottom), so there is no override for the function createFromTemplate . 这里的问题是尚未创建CDialog (高级类的构建顺序:从上到下),因此功能createFromTemplate没有覆盖。

If you need the function to be virtual then I guess the best option is to add a new protected method in CForm (lets call it initializeComponent ), which should be called from the constructor of CDialog 如果您需要将该函数虚拟化,那么我猜最好的选择是在CForm添加一个新的受保护方法(让我们将其称为initializeComponent ),应该从CDialog的构造函数中调用该方法。

class CForm {
    // .. stuff

protected:
    virtual void createFromTemplate(int paTemplate);

    void initializeComponent() {
        createFromTemplate()
    }   
};

class CDialog: public CForm {
    CDialog(...) : CForm(...) {
        initializeComponent();
    }   
};

My 2 cents 我的2美分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM