在派生类的外部访问基类中的成员时,会根据继承方式影响基类成员的访问级别
在派生类的外部访问基类中的成员时,会根据继承方式影响基类成员的访问级别
访问控制
级别:public < protected < private
类的继承方式和内部的成员,取级别高的
#include <iostream>
#include "stdio.h"
#include "string"
using namespace std;
class Base
{
private:
int bnum1_;
public://在类的内部都可以访问到,通过成员方法或者友元函数。
//在派生类中只能访问到基类的public成员和protected成员。
int bnum2_;
void setNum(int bnum1, int bnum2, int bnum3)
{
bnum1_ = bnum1;
bnum2_ = bnum2;
bnum3_ = bnum3;
}
friend void printf(Base &b)
{
cout << " bnum1: " << b.bnum1_ << " bnum2: " << b.bnum2_ << " bnum3: " << b.bnum3_ << endl;
}
protected:
int bnum3_;
};
class Derived1 :private Base
{
public:
void printf()
{
//基类私有成员不能被访问。
cout << "bnum2: " << bnum2_ << " bnum3: " << bnum3_ << endl;
}
};
class Derived2 :protected Base
{
void printf()
{
//基类私有成员不能被访问。
cout << "bnum2: " << bnum2_ << " bnum3: " << bnum3_ << endl;//基类的公有成员和保护成员,在派生类中可以访问。
}
};
class Derived : public Base
{
private:
int bnum1_;
public:
int bnum2_;
protected:
int bnum3_;
};
int main()
{
Base b;
b.bnum2_=10;
//b.bnum1_=10;//不可以访问
//b.bnum3_=10;//不可以访问
b.setNum(20, 25, 30);
printf(b);
Derived d;
d.bnum2_ = 10;//可以被访问
}