原文链接:受保護的(protected)成員 在之前的範例中,類別的資料成員多設定為private成員,也就是私用成員,私用成員只能在類別物件中使用,不能直接透過物件來呼叫使用,而即使是繼承 了該類別的衍生類別也是如此,您只能透過該類別所提供的public函式成員來呼叫或設定私用成員。
然而有些時候,您希望繼承了基底類別的衍生類別,能夠直接存取呼叫基底類別中的成員,但不是透過public函式成員,也不是將它宣告為public,因 為您仍不希望這些成員被物件直接呼叫使用。
您可以宣告這些成員為「受保護的成員」(protected member),保護的意思表示存取它有條件限制以保護該成員,當您將類別成員宣告為受保護的成員之後,繼承它的類別就可以直接使用這些成員,但這些成員 仍然受到類別的保護,不可被物件直接呼叫使用。
要宣告一個成員成為受保護的成員,就使用”protected”關鍵字,並將成員宣告於它的下方,下面這個程式是個實際的例子,您將資料成員宣告為受保護 的成員,繼承它的類別就可以直接使用,而不用透過public函式成員來呼叫,這可以省去一些函式呼叫所帶來的負擔: Rectangle.h
class Rectangle { public: Rectangle() { _x = 0; _y = 0; _width = 0; _height = 0; } Rectangle(int x, int y, int width, int height) : _x(x), _y(y), _width(width), _height(height){ } int x() { return _x; } int y() { return _y; } int width() { return _width; } int height() { return _height; } int area() { return _width*_height; } // 受保護的member protected: int _x; int _y; int _width; int _height; };Cubic.h
#include "Rectangle.h" class Cubic : public Rectangle { public: Cubic() { _z = 0; _length = 0; } Cubic(int x, int y, int z, int length, int width, int height) : Rectangle(x, y, width, height) , _z(z), _length(length) { } int length() { return _length; } int volumn() { return _length*_width*_height; } protected: int _z; int _length; };main.cpp
#include <iostream> #include "Cubic.h" using namespace std; int main() { Cubic c1(0, 0, 0, 10, 20, 30); cout << "c1 volumn: " << c1.volumn() << endl; return 0; }在這個例子中,您可以看到直接使用繼承下來的受保護成員確實比較方便,函式成員也可以宣告為受保護的成員,對象通常是僅適用於類別中使用的一些內部處理函 式,這些函式對類別外部來說,可能是呼叫它並沒有意義或是有危險性,但您在衍生類別中仍可能使用到這些函式,所以通常會將之宣告為受保護的成員。