为什么我的虚拟方法没有被覆盖? [英] Why my virtual method is not overridden?

查看:61
本文介绍了为什么我的虚拟方法没有被覆盖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Base
{
public:
Base()
{
cout<<"base class"<<endl;
fun();
}
virtual void fun(){cout<<"fun of base"<<endl;}
};

class Derive:public Base
{
public:
Derive()
{
cout<<"derive class"<<endl;
fun();
}
void fun(){ cout<<"fun of derive"<<endl;}
};

void main()
{
Derive d;
}

输出为:

base class
fun of base
derive class
fun of derive

为什么第二行不是fun of derive?

推荐答案

在基类构造函数中调用fun()时,尚未构造派生类(在C ++中,类首先是构造的父类),因此系统尚无Derived实例,因此在Derived::fun()的虚拟功能表中没有条目.

When you call fun() in the base class constructor, the derived class has not yet been constructed (in C++, classes a constructed parent first) so the system doesn't have an instance of Derived yet and consequently no entry in the virtual function table for Derived::fun().

这就是为什么通常不赞成在构造函数中调用虚拟函数的原因,除非您明确地要调用虚拟函数的实现,该实现是当前实例化对象的一部分或一部分它的祖先.

This is the reason why calls to virtual functions in constructors are generally frowned upon unless you specifically want to call the implementation of the virtual function that's either part of the object currently being instantiated or part of one of its ancestors.

这篇关于为什么我的虚拟方法没有被覆盖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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