简体   繁体   English

从基类方法调用虚方法

[英]Calling a virtual method from a base class method

I want to call a overridden method from a base class method called by the derived class: 我想从派生类调用的基类方法调用重写方法:

class Base {
    Base();
    virtual void function override() {}
    void basefunction() {
        override();
    }

class Derived : public Base {
    Derived() {
        basefunction();
    }
    virtual void function override() {
        cout << "derived" << endl;
    }
}

main() {
    Base* d = new Derived();
}

The constructor of Derived call the basefunction, which should call the overridden function "override()" from the derived class. Derived的构造函数调用basefunction,它应该从派生类调用重写函数"override()"

But it doesn't. 但事实并非如此。 It calls Base::override(). 它调用Base :: override()。 I understand why this function is called, but how can I implement my issue, that the basefunction calls the override function from the derived class? 我理解为什么调用这个函数,但是如何实现我的问题,basefunction从派生类调用override函数?

If the override function is defined as pure virtual the declaration in the main function is not allowed. 如果覆盖函数被定义为纯虚函数,则不允许使用main函数中的声明。

  • Is it possible to show us the code you are using? 是否可以向我们展示您正在使用的代码? The one you give has to be completed in order to be compilable. 您提供的那个必须完成才能编译。

  • When completed in the obvious way, I get the result I expect: display of "derived". 当以明显的方式完成时,我得到了我期望的结果:显示“派生”。

  • There is something related which could be the problem you see, or it could be unrelated. 有一些相关的东西可能是你看到的问题,或者它可能是无关的。 During the execution of the constructor and the destructor, the dynamic type is the same as the type of the constructor/destructor. 在执行构造函数和析构函数期间,动态类型与构造函数/析构函数的类型相同。 So if you have the call to basefunction in Base() instead of in Derived(), indeed it is Base::override which is called and not Derived::override. 因此,如果你在Base()而不是Derived()中调用basefunction,实际上它是被调用的Base :: override而不是Derived :: override。 During the execution of Base::Base(), Derived's members have not been constructed yet and it would be dangerous to call a member which could access them. 在执行Base :: Base()期间,Derived的成员尚未构建,调用可以访问它们的成员会很危险。

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

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