Team LiB
Previous Section Next Section

Chapter Summary


Most of C++ is applicable to a wide range of problemsfrom those solvable in a few hour's time to those that take years of development by large teams. Some features in C++ are most applicable in the context of large-scale problems: exception handling, namespaces, and multiple or virtual inheritance.

C++ 的大部分特征都可以应用于范围很广的问题——从几小时便可解决的问题到大团队花几年时间才能解决的问题。其中有一些特征则最适用于大规模问题的情况,这些特征包括异常处理、命名空间、多重继承和虚继承。

Exception handling lets us separate the error-detection part of the program from the error-handling part. Section 6.13 (p. 215) introduced exception handling and this chapter completes our coverage of exceptions. When an exception is thrown, the current executing function is suspended and a search is started to find the nearest catch clause. Local variables defined inside functions that are exited while searching for a catch clause are destroyed as part of handling the exception. The fact that objects are destroyed gives rise to an important programming technique known as "resource allocation is initialization" (RAII).

通过异常处理我们能够将程序的错误检测部分与错误处理部分分开。异常处理是在第 6.13 节中引入的,本章最终完成了对异常处理的讨论。在抛出异常的时候,会终止当前正在执行的函数并开始查找最近的 catch 子句,在查找 catch 子句的时候,作为异常处理的一部分,将撤销退出函数内部定义的局部变量。这种撤销对象提供了一个重要的编程技术,称为“资源分配即初始化”(RAII)。

Namespaces are a mechanism for managing large complex applications built from code produced by independent suppliers. A namespace is a scope in which objects, types, functions, template, and other namespaces may be defined. The standard library is defined inside the namespace named std.

命名空间是一种机制,用于管理用独立供应商开发的代码建立的大型复杂应用程序。一个命名空间就是一个作用域,其中可以定义对象、类型、函数、模板和其他命名空间。标准库就定义在名为 std 的命名空间中。

Names in a namespace may be made available to the current scope one at a time via a using declaration. Alternatively, but much less safely, all the names in a namespace may be brought into the current scope via a using directive.

通过 using 声明,当前作用域中就都可以访问某个命名空间中的名字了。当然,也可以通过 using 指示将一个命名空间中的所有名字带入当前作用域,但这种做法很不安全。

Conceptually, multiple inheritance is a simple notion: A derived class may inherit from more than one direct base class. The derived object consists of the derived part and a base part contributed by each of its base classes. Although conceptually simple, the details can be more complicated. In particular, inheriting from multiple base classes introduces new possiblities for name collisions and resulting ambiguous references to names from the base part of an object.


When a class inherits from more than one immediate base class, it is possible that those classes may themselves share another base class. In cases such as this, the intermediate classes can opt to make their inheritance virtual, which states a willingness to share its virtual base class with other classes in the hierarchy that inherit virtually from that same base class. In this way there is only one copy of the shared virtual base in a subsequently derived class.


Team LiB
Previous Section Next Section