一、继承中的访问级别学习:
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的意义
--修饰的成员不能被外界直接访问
-- 修饰的成员可以被子类直接访问