代碼實現
#include <iostream>
#include <string>
using namespace std;
class Parent
{
protected:
int mv;
public:
Parent()
{
mv = 100;
}
int value()
{
return mv;
}
};
class Child : public Parent
{
public:
int addValue(int v)
{
mv = mv + v;
}
};
int main()
{
Parent p;
cout << "p.mv = " << p.value() << endl;
p.mv = 1000; // error
Child c;
cout << "c.mv = " << c.value() << endl;
c.addValue(50);
cout << "c.mv = " << c.value() << endl;
c.mv = 10000; // error
return 0;
}
運行結果:
root@txp-virtual-machine:/home/txp# g++ test.cpp
test.cpp: In function ‘int main()’:
test.cpp:9:9: error: ‘int Parent::mv’ is protected
int mv;
^
test.cpp:37:8: error: within this context
p.mv = 1000; // error
^
test.cpp:9:9: error: ‘int Parent::mv’ is protected
int mv;
^
test.cpp:47:7: error: within this context
c.mv = 10000; // error
注解:這里我們把父類的屬性private修改成protect,這里我們注意到在子類里面的方法中是可以使用父類中的屬性mv了,只不過在int main()函數中,使用父類和子類定義的對象,均不可以對父類中的屬性mv進行訪問,這一點要注意。
3、為什么面向對象中需要protect?
我們還是用生活中的例子來理解,每個人的個人隱私,是不能泄露的,也就是我們c++中的private關鍵字;而你身上穿的衣服,每個人都可以知道,也就是c++中的public關鍵字;最后我們的protect關鍵字,為啥c++中會需要它,我想還是跟生活中有關(所以說,面向對象的編程,非常貼近生活),比如說,家庭開會,有些事情就不能讓外人知道,但是自己家人就可以知道,所以這跟protect關鍵字的用法非常像,也就是說,protect關鍵鑒于private和public之間。