virtual function calls in constructor and destructor(构造函数和析构函数中的虚函数调用)
问题描述
class Base
{
public:
Base(){Foo();}
~Base(){Foo();}
virtual void Foo(){std::cout<<"base";}
};
class Derived: public Base
{
public:
Derived(){Foo();}
~Derived(){Foo();}
void Foo(){std::cout<<"derived";}
};
//main
{
Derived d;
}
知道为什么这段代码会打印出基础"和派生"吗?
我明白建议不要将虚函数调用放在构造函数或析构函数中,我只是想知道为什么上面的代码会有这种行为.谢谢
Any idea why this code prints out "base" and "derived"?
I understand the advice is not to put virtual function calls inside constructor or desctructor, I just want to know why the above code would have the behaviour. Thanks
推荐答案
在执行类 C 的构造函数期间,尚未构造派生的子对象.因此,正在构造的对象的动态类型是构造函数的静态类型,即C.任何virtual 函数都将被分派,就好像对象是C 类型一样.同样,当派生类型的对象被销毁并且 C 的析构函数正在运行时,所有派生的子对象都已经被销毁,并且该类型的行为就好像它属于 类型一样C.
During execution of the constructor of a class C, the derived subobjects are not, yet, constructed. Thus, the dynamic type of the object under construction is the static type of the constructor, i.e., C. Any virtual function will be dispatched as if the object is type C. Likewise, when an object of a derived type is destroyed and the destructor of C is being run, all the derived subobjects are already destroyed and, again, the type behaves as if it is of type C.
也就是说,在构造和销毁过程中,涉及继承的对象的类型发生了变化!动态调度被安排为匹配对象的当前类型.
That is, during construction and destruction the type of an object involving inheritance changes! The dynamic dispatch is arranged to match the current type of the object.
这篇关于构造函数和析构函数中的虚函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:构造函数和析构函数中的虚函数调用
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
