C++ 中的动态绑定
我需要对 C++ 中的动态绑定进行一些澄清。我对以下内容感到困惑:
在 C 中,您可以拥有一个函数指针数组和一个函数指针数组。 分配相同签名的不同功能 根据索引调用它们; 这是动态绑定吗?
在 C++ 中,您可以拥有基类指针数组,但您可以通过将派生类对象地址分配给基类指针数组来调用派生类的不同函数。 通过使用虚函数,这是动态绑定吗?
哪个术语是正确的 -
动态绑定
或链接时绑定
?
I need some clarification on dynamic binding in C++ .I'm confused about the following:
In C you can have an array of function pointers & assign different functions of the same signature & call them based on the index; is this Dynamic binding?
In C++ you can have an array of base class pointers but you can call different functions of the derived class, by assigning the derived class objects addresses to a base-class array of pointers & by using virtual functions, Is this Dynamic Binding?
Which term is correct -
Dynamic binding
orLink-Time Binding
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您尝试过用 C 语言编写代码吗? 你为此使用了哪个编译器? C 语言中不能有两个同名的函数。
Have you tried writing a code In C language? Which compiler you used for this? You can't have two functions with same name in C language.
您将动态绑定的概念与实现混淆了。 动态绑定,即根据接收对象的类型选择调用哪个方法,可以使用某种形式的动态调度来实现,即您的(1),但我们通常定义名称仅指情况(2)。
You're confusing the concept of dynamic binding with the implementation. Dynamic binding, i.e. choosing which method to call based on the receiving object's type, may be implemented using some form of dynamic dispatch, i.e. your (1), but we generally define the name to only refer to situation (2).
答案
Answers
我将这两种用途称为动态绑定。 在 C++ 中,该语言为您提供了一种机制,这样您就不必像在 C 中那样自行开发。
(我曾经使用过一个应用程序,其中每个主要对象都伴随着一个
struct 传递
其字段是函数指针。该结构的目的是允许应用程序实现运行时动态绑定 - 即在运行时更改对象的分配函数,具体取决于据我所知,这个“功能”从未被利用过。)I'd call both of these uses of dynamic binding. In C++, the language is giving you the mechanism, so that you don't have to roll your own as you do in C.
(I once worked with an app in which every major object was passed around accompanied by a
struct
whose fields were function pointers. The struct's purpose was to allow the app to implement run-time dynamic binding -- that is, to change the assigned functions for the object at runtime, depending on the object's state. This "feature" was never taken advantage of, so far as I know.)动态绑定是在运行时将接口绑定到其实现 - 程序自动决定调用哪个代码作为接口实现的任何情况。 所以一般来说1)和2)都是动态绑定,但这个术语通常只用于2)。
链接时绑定(又名早期绑定)与动态绑定(又名后期绑定)相反。 在链接时绑定中,编译器/链接器确切地知道要调用什么代码并生成对该代码的直接调用。 在动态绑定中,编译器/链接器不知道 - 确切的实现是在运行时确定的。
Dynamic binding is binding interface to its implementation at runtime - any situation when the program automatically decides which code to call as interface implementation. So generally speaking both 1) and 2) are dynamic binding, but the term is usually only used for 2).
Link-time binding (aka early binding) is the opposite of dynamic binding (aka late binding). In link-time binding the compiler/linker knows exactly what code to call and gererates a direct call of that code. In dynamic binding the compiler/linker doesn't know that - exact implementation is determined at runtime.