问题描述
嗨
我正在运行以下多态性的C ++代码:
class 基本 { 公共: 虚拟 无效 f1 (){std: :cout<< " 基本f1" << std :: endl;} 无效 f (){std :: cout<< " 基本f" << std :: endl;} }; class 派生: public Base { 公共: 虚拟 无效 f (){std: :cout<< " 派生f" << std :: endl;} }; class DDerived: public Derived { 公共: 虚拟 无效 f (){std: :cout<< " DDerived f" << std :: endl;} };
基础 * p_base = 新 DDerived(); p_base-> f (); 派生 * p_derived = 新 DDerived(); p_derived-> f ();
结果是:
基本f DDerived f
可以预期,因为Base在其虚拟函数表中没有f(),而Derived应该具有f().
但是它是如何工作的呢?
Derived和DDerived应该从Base继承虚拟函数表,该表包含f1()而不是f().
但是Derived和DDerived在它们的虚拟函数表中也应该有f().他们有2个不同的虚拟表吗?
我使用Visual Studio 2008调试器,但只看到一个虚拟函数表,它不包含f().
虚拟函数f()在哪里?
谢谢!
Moti
Hi
I''m running the following C++ code of polymorphism:
class Base { public: virtual void f1() {std::cout << "base f1" << std::endl;} void f() {std::cout << "base f" << std::endl;} }; class Derived : public Base { public: virtual void f() {std::cout << "Derived f" << std::endl;} }; class DDerived : public Derived { public: virtual void f() {std::cout << "DDerived f" << std::endl;} };
Base* p_base = new DDerived(); p_base->f(); Derived* p_derived = new DDerived(); p_derived->f();
and the result is:
base f DDerived f
it is expected since Base doesn''t have f() in its virtual function table, and Derived should have it.
But how does it work?
Derived and DDerived should inherit the virtual function table from Base, that contains f1() and not f().
But Derived and DDerived should also have f() in their virtual function table. Do they have 2 different virtual tables?
I use Visual Studio 2008 debugger and I see only one virtual function table and it doesn''t contain f().
Where is the virtual function f() located?
Thanks!
Moti
这篇关于派生类中的虚拟函数,但基类中的非虚拟函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!