一、繼承中的訪問級別學習:
1、子類是否可以直接訪問父類的私用成員嗎?
從面向對象理論角度來看:
子類擁有父類的一切屬性和行為,也就是說,子類能夠直接訪問父類的私有成員。
從c++的語法角度看:
外界不能直接訪問類的private成員,也就是說,子類不能直接訪問父類的私用成員。
代碼示例:
#include <iostream>
#include <string>
using namespace std;
class Parent
{
private:
int mv;
public:
Parent()
{
mv = 100;
}
int value()
{
return mv;
}
};
class Child : public Parent
{
public:
int addValue(int v)
{
mv = mv + v; // 如何訪問父類的非公有成員
}
};
int main()
{
return 0;
}
輸出結果:
root@txp-virtual-machine:/home/txp# g++ test.cpp
test.cpp: In member function ‘int Child::addValue(int)’:
test.cpp:9:9: error: ‘int Parent::mv’ is private
int mv;
^
test.cpp:27:9: error: within this context
mv = mv + v; // 如何訪問父類的非公有成員
^
test.cpp:9:9: error: ‘int Parent::mv’ is private
int mv;
^
test.cpp:27:14: error: within this context
mv = mv + v; // 如何訪問父類的非公有成員
^
注解:我們可以看到子類不能直接訪問到父類里面的屬性
2、繼承中的訪問級別關系
面向對象中的訪問級別不只是public和private
可以定義protected訪問級別
關鍵字protect的意義
--修飾的成員不能被外界直接訪問
-- 修飾的成員可以被子類直接訪問