Team LiB
Previous Section Next Section

Chapter Summary

小结

The ideas of inheritance and dynamic binding are simple but powerful. Inheritance lets us write new classes that share behavior with their base class(es) but redefine that behavior as needed. Dynamic binding lets the compiler decide at run time which version of a function to run based on an object's dynamic type. The combination of inheritance and dynamic binding lets us write type-independent programs that have type-specific behavior.

继承和动态绑定的思想,简单但功能强大。继承使我们能够编写新类,新类与基类共享行为但重定义必要的行为。动态绑定使编译器能够在运行时根据对象的动态类型确定运行函数的哪个版本。继承和动态绑定的结合使我们能够编写具有特定类型行为而又独立于类型的程序。

In C++, dynamic binding applies only to functions declared as virtual when called through a reference or pointer. It is common for C++ programs to define handle classes to interface to an inheritance hierarchy. These classes allocate and manage pointers to objects in the inheritance hierarchy, thus obtaining dynamic behavior while shielding user code from having to deal with pointers.

在 C++ 中,动态绑定在通过引用或指针调用时才能应用于声明为虚的函数。C++ 程序定义继承层次接口的句柄类很常见,这些类分配并管理指向继承层次中对象的指针,因此能够使用户代码在无须处理指针的情况下获得动态行为。

Inherited objects are composed of base-class part(s) and a derived-class part. Inherited objects are constructed, copied, and assigned by constructing, copying, and assigning the base part(s) of the object before handling the derived part. Because a derived object contains a base part, it is possible to convert a reference or pointer to a derived type to a reference or pointer to its base type.

继承对象由基类部分和派生类部分组成。继承对象是通过在处理派生部分之前对对象的基类部分进行构造、复制和赋值,而进行构造、复制和赋值的。因为派生类对象包含基类部分,所以可以将派生类型的引用或指针转换为基类类型的引用或指针。

Base classes usually should define a virtual destructor even if the class otherwise has no need for a destructor. The destructor must be virtual if a pointer to a base is ever deleted when it actually addresses a derived-type object.

即使另外不需要析构函数,基类通常也应定义一个虚析构函数。如果经常会在指向基类的指针实际指向派生类对象时删除它,析构函数就必须为虚函数。

Team LiB
Previous Section Next Section