1. 前言
我们知道,对外部来讲,一个类的private
和protected
成员,外部都不能直接访问。那么,对子类来说呢?子类如果以public
方式继承父类,它还是不能直接访问private
成员,并且虽然它可以访问protected
成员,也是有限制条件的,就是只能在 类内 类内 类内通过 它自己的实例对象 它自己的实例对象 它自己的实例对象访问。
2. 举例
2.1 外部不能直接访问举例
#include<iostream>
using namespace std;
// 基类
class Base {
protected:
int prot_mem;
};
int main()
{
Base b;
b.prot_mem = 0; // 会报错
return 0;
}
2.2 子类不能访问举例
#include<iostream>
using namespace std;
// 基类
class Base {
protected:
int prot_mem;
};
// 派生类
class Derive :public Base {
private:
void f2(Base&);
int j;
};
void Derive::f2(Base& b) {
b.prot_mem = 0; // 会报错
}
int main()
{
Derive d;
d.prot_mem = 0; // 会报错
return 0;
}
2.3 子类可以访问举例
#include<iostream>
using namespace std;
// 基类
class Base {
protected:
int prot_mem;
};
// 派生类
class Derive :public Base {
private:
void f1(Derive&);
int j;
};
void Derive::f1(Derive& d) {
d.j = d.prot_mem = 0; // 可以
}
int main()
{
return 0;
}