Class Design and Protected Members

C++ Primer 4/e在Defining Base and Derived Classes這個地方有一個關鍵概念:『In the absence of inheritance, a class has two kinds of users: members of the class itself and the users of that class. This separation between kinds of users is reflected in the division of the class into private and public access levels. Users may access only the public interface; class members and friends may access both the public and private members.

Under inheritance, there is now a third kind of user of a class: programmers who will define new classes that are derived from the class. The provider of a derived class often (but not always) needs access to the (ordinarily private) base-class implementation. To allow that access while still preventing general access to the implementation, an additional access label, protected, is provided. The data and function members in a protected section of a class remain inaccessible to the general program, yet are accessible to the derived class. Anything placed within a private section of the base class is accessible only to the class itself and its friends. The private members are not accessible to the derived classes.

When designing a class to serve as a base class, the criteria for designating a member as public do not change: It is still the case that interface functions should be public and data generally should not be public. A class designed to be inherited from must decide which parts of the implementation to declare as protected and which should be private. A member should be made private if we wish to prevent subsequently derived classes from having access to that member. A member should be made protected if it provides an operation or data that a derived class will need to use in its implementation. In other words, the interface to the derived type is the combination of both the protected and public members.』


有了繼承之後,class多出第三種使用者:derived classes。Derived class經常(但非總是)需要存取base class的實作部份(一般為private)。為准許此種行為並避免一般人存取時作部份,C++另外提供了一個存取級別protected。此級別的成員函式和成員變數不能被一般程式取用,但可被derived class存取。至於base class的private區段內的任何東西只能被class自身及其friends取用,無法被derived classes存取。

設計base class時「成員是否該為public」的判斷準則並未改變:介面函式應該設計為public,資料通常不該是public。設計base class時還必須決定哪些實作應宣告為protected,哪些應宣告為private。如果想避免讓derived classes存取某成員,那個成員就該是private。如果某成員提供的是「derived class需要用到的操作成員或資料」,那個成員就該是protected。換句話說,開放給derived class的是「protected 和public成員的聯集」。』

聯集?這一段英文是the interface to the derived type is the combination of both the protected and public members,不是在講介面是protected跟public的組合嗎?怎跟聯集扯上關係?嗯!可能沒有跟數學的聯集有關係,不過還是很讓人疑惑?




發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *