继承编译时还是运行时?
在c++中,继承发生在运行时还是编译时?
例子?
In c++, does inheritance occur at run time or compile time?
Examples?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
在c++中,继承发生在运行时还是编译时?
例子?
In c++, does inheritance occur at run time or compile time?
Examples?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
在 C++ 中,自身继承(无多态性)是编译时功能。在编译后的代码中, 和 之间几乎没有区别
,
除了访问其成员的偏移量之外,不会有任何关于
bar
与foo
关系的“知识”在编译的二进制文件中。但是,当您添加多态性(即
虚拟
函数,允许dynamic_cast<>()) 到图片。它允许后期绑定:将调用哪个函数是在运行时决定的。当然,这需要数据结构来执行此操作(通常使用所谓的虚拟表),并且这些数据结构在运行时访问以便确定要调用哪个函数。
此外,
虚拟
基类需要运行时支持才能使用派生对象访问它们。如果您对某些 C++ 功能的运行时成本感兴趣,您可能需要尝试获取 C++ 对象模型内部 作者:Stanley Lippman。这是一本老书,但如果您想了解虚拟成员函数通常是如何实现的,以及在多继承场景中基对象通常如何在内存中布局,以及所有这些如何影响性能,您可以在本书中找到深入的讨论此类主题。
In C++, inheritance in itself (without polymorphism) is a compile-time feature. In the compiled code, there will be little or no difference between
and
Except for offsets to access their members, there will not be any "knowledge" about how
bar
relates tofoo
in the compiled binary.This is different, however, when you add polymorphism (i.e.,
virtual
functions, allowingdynamic_cast<>()
) to the picture. It allows late binding: which exact function will be called is decided at runtime. Of course, this requires data structures to perform this (usually employing so-called virtual tables), and those data structures are accessed at runtime in order to determine which function to call.Also,
virtual
base classes require runtime support in order to access them withing derived objects.If you are interested in the runtime costs of certain C++ features, you might want to try to get hold of a copy of Inside the C++ Object Model by Stanley Lippman. It's an old book, but if you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.
简而言之,
关键字
virtual
指定编译器或运行时是否应该执行提升。In simplest terms,
The keyword
virtual
specifies whether the compiler or the runtime should do the lifting.这取决于“发生”的含义......它是在编译时定义的,但在运行时执行(虚函数表等)。
It depends on what you mean by "occurs"... it is defined at compile time but executed at run time (vtables etc).
有一些技术可以在编译时和运行时实现继承。
There are techniques that implement inheritance at both compile and run time.