C++ Primer(第5版)- Chapter 7. Classes -001
In C++ we use classes to define our own data types. By defining types that mirror concepts in the problems we are trying to solve, we can make our programs easier to write, debug, and modify.
在 C++语⾔中,我们使⽤类定义⾃⼰的数据类型(data types)。通过定义新的类型来反映待解决问题中的各种概念,可以使我们更容易编写、调试和修改程序。
This chapter continues the coverage of classes begun in Chapter 2. Here we will focus on the importance of data abstraction, which lets us separate the implementation of an object from the operations that that object can perform. In Chapter 13 we’ll learn how to control what happens when objects are copied, moved, assigned, or destroyed. In Chapter 14 we’ll learn how to define our own operators.
本章是第2章关于类的话题的延续,主要关注(focus on)数据抽象(data abstraction)的重要性,数据抽象能帮助我们将对象的具体实现(the implementation of an object)与对象所能执⾏的操作分离开来。第13章将讨论如何控制对象拷贝(copy)、移动(move)、赋值(assign)和销毁(destroy)等⾏为。在第14章中我们将学习如何⾃定义运算符。
The fundamental ideas behind classes are data abstraction and encapsulation. Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation. The interface of a class consists of the operations that users of the class can execute. The implementation includes the class’ data members, the bodies of the functions that constitute the interface, and any functions needed to define the class that are not intended for general use.
类的基本思想(fundamental ideas)是数据抽象(data abstraction)和封装(encapsulation)。数据抽象是⼀种依赖于(rely on)接口(interface)和实现(implementation)分离的编程(以及设计)技术。类的接口包括(consist of)⽤户所能执⾏的操作;类的实现则包括(include)类的数据成员(the class’ data members)、负责接口实现(constitute the interface)的函数体(bodies of the functions)以及定义类所需的各种私有函数(that are not intended for general use)。
Encapsulation enforces the separation of a class’ interface and implementation. A class that is encapsulated hides its implementation—users of the class can use the interface but have no access to the implementation.
封装(Encapsulation)实现了(enforce)类的接口(interface)和实现(implementation)的分离(separation)。封装后(that is encapsulated)的类隐藏了(hide)它的实现细节(implementation)。也就是说,类的⽤户(users of the class)只能使⽤接口(interface)⽽⽆法访问(have no access to)实现部分(the implementation)。
A class that uses data abstraction and encapsulation defines an abstract data type. In an abstract data type, the class designer worries about how the class is implemented. Programmers who use the class need not know how the type works. They can instead think abstractly about what the type does.
类要想实现数据抽象(data abstraction)和封装(encapsulation),需要⾸先定义⼀个抽象数据类型(an abstract data type)。在抽象数据类型中,由类的设计者负责考虑(worry about)类的实现过程。使⽤该类的程序员则只需要抽象地思考(think abstractly about)类型做了什么,⽽⽆须了解类型的⼯作细节 。