简体   繁体   English

C ++动态绑定

[英]C++ dynamic binding

C ++如何实现动态绑定以及静态类型?

When you have a pointer to an object, the object may actually be of a class that is derived from the class of the pointer (eg, a Vehicle* that is actually pointing to a Car object; this is called "polymorphism"). 当您有一个指向对象的指针时,该对象实际上可能是从该指针的类派生的类(例如,实际上指向Car对象的Vehicle *;这被称为“多态”)。 Thus there are two types: the (static) type of the pointer (Vehicle, in this case), and the (dynamic) type of the pointed-to object (Car, in this case). 因此,有两种类型:指针的(静态)类型(在这种情况下,为车辆)和指向对象的(动态)类型(在这种情况下,为Car)。

Static typing means that the legality of a member function invocation is checked at the earliest possible moment: by the compiler at compile time. 静态类型化意味着成员函数调用的合法性要尽早检查:由编译器在编译时检查。 The compiler uses the static type of the pointer to determine whether the member function invocation is legal. 编译器使用指针的静态类型来确定成员函数调用是否合法。 If the type of the pointer can handle the member function, certainly the pointed-to object can handle it as well. 如果指针的类型可以处理成员函数,则指向对象的对象当然也可以处理它。 Eg, if Vehicle has a certain member function, certainly Car also has that member function since Car is a kind-of Vehicle. 例如,如果Vehicle具有某种成员功能,那么Car当然也具有该成员功能,因为Car是一种车辆。

Dynamic binding means that the address of the code in a member function invocation is determined at the last possible moment: based on the dynamic type of the object at run time. 动态绑定意味着成员函数调用中的代码地址是在最后可能的时刻确定的:基于运行时对象的动态类型。 It is called "dynamic binding" because the binding to the code that actually gets called is accomplished dynamically (at run time). 之所以称为“动态绑定”,是因为与实际调用的代码的绑定是动态(在运行时)完成的。 Dynamic binding is a result of virtual functions. 动态绑定是虚拟功能的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM