Defining the Sales_item Class
Evidently what we need is the ability to define a data type that will have these three data elements and the operations we used in Chapter 1. In C++(www.cppentry.com), the way we define such a data type is to define a class:
- class Sales_item {
- public:
private: std::string isbn; unsigned units_sold; double revenue; };
A class definition starts with the keyword class followed by an identifier that names the class. The body of the class appears inside curly braces. The close curly must be followed by a semicolon.
It is a commonmistake among newprogrammers to forget the semicolon at the end of a class definition.
漏写分号是一个常见错误,而且错误信息不一定准确。特别是如果在头文件中漏写了class 定义末尾的分号,那么出错的位置有可能是在包含这个头文件的.cc 文件里,这时候要记得去检查头文件。本节练习2.8 一定要上机实验。
The class body, which can be empty, defines the data and operations that make up the type. The operations and data that are part of a class are referred to as its members. The operations are referred to as the member functions (Section 1.5.2, p. 24) and the data as data members.
The class also may contain zero or more public or private access labels. An access label controls whether a member is accessible outside the class. Code that uses the class may access only the public members.
When we define a class, we define a new type. The class name is the name of that type. By naming our class Sales_item we are saying that Sales_item is a new type and that programs may define variables of this type.
Each class defines its own scope (Section 2.3.6, p. 54). That is, the names given to the data and operations inside the class body must be unique within the class but can reuse names defined outside the class.
Class Data Members
The data members of a class are defined in somewhat the same way that normal variables are defined. We specify a type and give the member a name just as we do when defining a simple variable:
- std::string isbn;
- unsigned units_sold;
- double revenue;
Our class has three data members: a member of type string named isbn, an unsigned member named units_sold, and a member of type double named revenue. The data members of a class define the contents of the objects of that class type. When we define objects of type Sales_item, those objects will contain a string, an unsigned, and a double.
There is one crucially important difference between how we define variables and class data members: We ordinarily cannot initialize the members of a class as part of their definition. When we define the data members, we can only name them and say what types they have. Rather than initializing data members when they are defined inside the class definition, classes control initialization through special member functions called constructors (Section 2.3.3, p. 49). We will define the Sales_item constructors in Section 7.7.3 (p. 262).