OOP的三大特色:『繼承,封裝,多型』,C++使用了4個class access label實踐封裝:『public、protected、private、friend』。

4個access label的使用時機如下:
public:當資料可以給user、自己和derived class存取時使用。
protected:當資料不可以給user存取,只能給自己和derived class存取時使用。

private:當資料不可以給user和derived class使用,只可以給自己存取時使用。

friend:指定一個global function可存取private資料。

其中較難理解的是friend,這在其他語言都沒有,其實friend在C++也只用在operator overloading,其他地方則不應該使用,因為違反了OOP封裝的原則。

以下範例demo四種class access label的用法:

 1}


執行結果

(原創) C++的4個Class Access Label (C/C++)123456
(原創) C++的4個Class Access Label (C/C++)
123456


程式的架構Student為ABC,Bachelor繼承了Student,studentNo為學號,若使用了14行的private,則Bachelor::getStudentNo()將無法存取studentNo,必須改成15行的protected,而constructor和member function,因為本來就是要給user存取的,所以放在public,比較特別的是18行Student的Constructor放在protected,因為Student為ABC,不能被建立成object,所以constructor不應該為public,只要是protected供derived class呼叫即可,當然寫成public也不會造成程式錯誤。

20行的friend,主要是operator overloading給<<使用,因為是global function,又要讓<<存取private data,只好宣告此global function為friend,再次強調,C++應該只在operator overloading使用friend,其他地方亂使用都會違反OOP的封裝原則。

相关文章: