Access Labels
Access labels control whether code that uses the class may use a given member. Member functions of the class may use any member of their own class, regardless of the access level. The access labels, public and private, may appear multiple times in a class definition. A given label applies until the next access label is seen.
注意:虽然private/public通常被翻译为“ 私有/ 公有”,但其实它们的意思更接近“私用/ 公用”,因为private/public 限制的不是所有权,而是使用权。无论是private 还是public 的成员,都是class 私自拥有的。
The public section of a class defines members that can be accessed by any part of the program. Ordinarily we put the operations in the public section so that any code in the program may execute these operations.
Code that is not part of the class does not have access to the private members. By making the Sales_item data members private, we ensure that code that operates on Sales_item objects cannot directly manipulate the data members. Programs, such as the one we wrote in Chapter 1, may not access the private members of the class. Objects of type Sales_item may execute the operations but not change the data directly.
Using the struct Keyword
C++(www.cppentry.com) supports a second keyword, struct, that can be used to define class types. The struct keyword is inherited from C.
If we define a class using the class keyword, then any members defined before the first access label are implicitly private; if we use the struct keyword, then those members are public. Whether we define a class using the class keyword or the struct keyword affects only the default initial access level.
We could have defined our Sales_item equivalently by writing
- struct Sales_item {
-
There are only two differences between this class definition and our initial class definition: Here we use the struct keyword, and we eliminate the use of public keyword immediately following the opening curly brace. Members of a struct
are public, unless otherwise specified, so there is no need for the public label.
The only difference between a class defined with the class keyword or the struct keyword is the default access level: By default, members in a struct are public; those in a class are private.