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

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/* 
 2(C) OOMusou 2007 http://oomusou.cnblogs.com
 3
 4Filename    : ClassAccessLabel.cpp
 5Compiler    : Visual C++ 8.0 / ISO C++
 6Description : Demo class access label
 7Release     : 01/23/2007 1.0
 8*/

 9#include <iostream>
10
11using namespace std;
12
13class Student {
14// private :
15protected// must use protected to allow derived class to access.
16  int studentNo;
17protected:
18  Student(int studentNo = 0) : studentNo(studentNo) {}
19public:
20  friend ostream& operator<<(ostream&const Student&); // use global function
21}
;
22
23class Bachelor : public Student {
24public:
25  Bachelor(int studentNo = 0) : Student(studentNo) {} // Call base class constructor
26public:
27  int getStudentNo() {
28     return this->studentNo;
29  }

30}
;
31
32ostream& operator<<(ostream& outconst Student& student) {
33  out << student.studentNo << endl;
34
35  return out;
36}

37
38
39int main() {
40  Bachelor John(123456);
41  cout << John.getStudentNo() << endl;
42  cout << John << endl;
43}


執行結果

123456
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的封裝原則。

posted on 2007-01-23 11:06  真 OO无双  阅读(2007)  评论(0编辑  收藏  举报

导航