This article is one of <Effective C++> reading notes.
Part 4: Designs and Declarations
Item 22: Declare data members private.
Things To Remember
- Declare data members private. It gives clients syntactically uniform access to data, affords fine-grained access control, allows invariants to be enforced, and offers class authors implementation flexibility.
- protected is no more encapsulated than public.
Key Words
syntactic consistency (语法一致性):
Ways to facilitate the correct use include consistency in interfaces and behavioral compatibility with build-in types. [Item 18]
fine-grained access control:
Coarse-grained vs. fine-grained access control.
A class invariant is an invariant used to constrain objects of a class. Methods of the class should preserve the invariant. The class invariant constrains the state stored in the object.
Key Points
Suppose we have a protected data member, and we eliminate it, then all the derived classes that use it might be broken now.
Unencapsulated means unchangeable, especially for classes that are widely used. So from an encapsulation point of view, there are really only two access levels: private (which offers encapsulation) and everything else (which doesn’t). [see alse <The Design and Evolution of C++>]
比 private 更彻底的方案是把私有部分全部放在一个私有的内部类中,并把私有类的定义从公开的头文件里删掉,只被实现所见。[Item 31]
Code
|
|