Parent类可以调用其子类的函数版本 [英] Possible for a Parent class to call its child class version of a function

查看:201
本文介绍了Parent类可以调用其子类的函数版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类MyScreen&我想总是在其构造函数中调用initComponents()函数,即使是这个类的子类。但是如果子类重写了initComponents()函数,那么我想让MyClass调用initComponents()的子类版本而不是initComponents()的超类(MyScreen) / p>

是否可以从MyClasses构造函数中执行此操作?

  class MyScreen 
{
public:
MyScreen()
{
//这个类的子类(&任何这个类的实例)应该总是从这个构造函数调用initComponents()
initComponents();
}

void initComponents()
{
//初始化mainLayout等,通常这个函数不会被覆盖,有时它会是
}

protected:
Layout * mainLayout;
};

class MenuScreen:public MyScreen
{
public:
MenuScreen:public MyScreen()
{
//我知道我可以从这里调用initComponents,但这只是一个例子,必须从基类调用某些事情
}

void initComponents()
{
//创建布局,设置主布局等。
mainLayout = new MenuLayout(...);
}
};


解决方案

你不应该那。问题是,当构造你的派生类的对象时,基类构造函数总是在派生类之前调用​​。这意味着派生对象还没有被创建,所以它的成员将不被初始化(这将可能也对v表有效,因此虚函数调用将不起作用)。请检查这篇文章



你应该明确地调用你的类的用户initComponents并标记它virtual


I have a base class MyScreen & I would like to always call the function initComponents() inside its constructor, even for sub classes of this class. But if the sub-class has overridden the initComponents() function, then I want MyClass to call the Sub-classes version of initComponents() not the super classes(MyScreen) version of initComponents().

Is it possible to do this from within MyClasses constructor?

class MyScreen
{
  public:
     MyScreen()
     {
        // a child of this class (& any instance of this class) should always call the initComponents() from this constructor
        initComponents(); 
     } 

     void initComponents()
     {
         // initialise mainLayout, etc, usually this function wont be overridden, sometimes it will be
     }

  protected:
      Layout *mainLayout;
};

class MenuScreen : public MyScreen
{
  public:
     MenuScreen : public MyScreen()
     {
        // I know I could just call initComponents from here, but this is just an example, somethings must be called from the base class
     } 

     void initComponents()
     {
         // create layout, set main layout etc.
         mainLayout = new MenuLayout(...);
     }
};

解决方案

You shouldn't (or maybe even cannot) do that. The problem is that when constructing an object of your derived class, the base-class constructor is always called before the derived class's. This means that the derived object is not yet created, so its members will not be initialized (this will probabely also be valid for the v-table, so virtual function calls won't work). check this article

Instead you should call the initComponents by the user of your class explicitly and mark it virtual

这篇关于Parent类可以调用其子类的函数版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆