(原創) 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的用法:
/* 2
(C) OOMusou 2007 http://oomusou.cnblogs.com3

4
Filename : ClassAccessLabel.cpp5
Compiler : Visual C++ 8.0 / ISO C++6
Description : Demo class access label7
Release : 01/23/2007 1.08
*/9
#include <iostream>10

11
using namespace std;12

13
class Student {14
// private :15
protected: // must use protected to allow derived class to access.16
int studentNo;17
protected:18
Student(int studentNo = 0) : studentNo(studentNo) {}19
public:20
friend ostream& operator<<(ostream&, const Student&); // use global function21
};22

23
class Bachelor : public Student {24
public:25
Bachelor(int studentNo = 0) : Student(studentNo) {} // Call base class constructor26
public:27
int getStudentNo() {28
return this->studentNo;29
}30
};31

32
ostream& operator<<(ostream& out, const Student& student) {33
out << student.studentNo << endl;34

35
return out;36
}37

38

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


Student(
浙公网安备 33010602011771号