纯虚函数位于 C++ 中的什么位置?
纯虚函数位于哪个虚表?在基类还是派生类中?
例如,每个类中的虚拟表是什么样的?
class Base {
virtual void f() =0;
virtual void g();
}
class Derived: public Base{
virtual void f();
virtual void g();
}
Which virtual table will be pure virtual function located? In the base class or derived class?
For example, what does the virtual table look like in each class?
class Base {
virtual void f() =0;
virtual void g();
}
class Derived: public Base{
virtual void f();
virtual void g();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
g++ -fdump-class-hierarchy layout.cpp
生成一个文件layout.cpp.class
。layout.cpp.class
的内容将显示以下内容:删除
f
的“纯粹性”将第五行更改为:g++ -fdump-class-hierarchy layout.cpp
produces a filelayout.cpp.class
. The content oflayout.cpp.class
will show the following:Removing the 'pureness' of
f
changes the fifth line to:每个类都有自己的 vtable。
Base
中的f
条目将为NULL
,Derived
中的条目将是指向代码的指针对于实施的方法。Each class has its own vtable. The entry for
f
inBase
will beNULL
, and the entry inDerived
will be a pointer to the code for the implemented method.vtable 条目将位于基类中。
为什么?因为您可以拥有一个保存派生类型对象地址的基指针类型,并且仍然调用基类型的指针变量上的方法。
纯虚函数只是告诉编译器,派生类型必须提供自己的实现,并且不能依赖基类的实现(如果基类中指定了实现)
The vtable entry will be in the base class.
Why? Because you can have a base pointer type that holds a derived type object's address and still call the method on the base type's pointer variable.
Pure virtual simply tells the compiler that the derived types must provide their own implementation, and they cannot rely on the base class' implementation (if one is even specified in the base class)
实际上两者都是。基类 vtable 将有一个用于纯虚函数的插槽,该插槽指向类似
pure_virtual_function_used()
存根的内容,该存根可能会中止程序,而派生类 vtable 将有一个指向实际实现的指针。In both actually. The base class vtable will have a slot for the pure virtual function pointing to something like
pure_virtual_function_called()
stub that would probably abort the program, while the derived class vtable will have a pointer to the actual implementation.