C++访问权限 public、protected、private 解析

时间:2021-03-17 15:05:26

参考:http://blog.csdn.net/complety/article/details/7493194

--访问权限的作用和目的:

1.控制外界是否可访问
2.控制子类是否可继承 

3.过滤子类继承时的权限(继承方式)

--三种访问权限
public:
外部使用时(实体对象)可见、子类及本类内部/ 成员函数、友元函数可见
protected:子类及本类内部/ 成员函数、友元函数可见

private:本类内部/ 成员函数、友元函数可见 (默认private

备注:访问权限主要体现在成员(变量/函数)对其 对象(外部)、类(内部)  可见性俩方面。

--三种继承方式:public继承、 protect继承 、private继承;(默认private继承)

继承之后基类成员最终权限 = Min(继承权限 ,原权限);
C++访问权限 public、protected、private 解析

 --例子从已下3方面谈:

1.基类成员对其对象的可见性:
2. 基类成员对派生类的可见性:
3. 基类成员对派生类对象的可见性:

#include <iostream>

class base{
public:
base(){
a = 0;
b = 1;
c = 2;
}
int a;
protected:
int b;
private:
int c;
};

class derived1 : public base{//public继承
public:
void fun(){//derived class可以访问public和protected member
std::cout<<base::a<<base::b<<std::endl;
//std::cout<<base::c;//不能访问
}
};
class derived2 : protected base{//protected继承
public:
void fun(){//derived class可以访问public和protected member
std::cout<<base::a<<base::b<<std::endl;
// std::cout<<base::c;//不能访问
}
};
class derived3 : private base{//private继承
public:
void fun(){//derived class可以访问public和protected member
std::cout<<base::a<<base::b<<std::endl;
// std::cout<<base::c;//不能访问
}
};
class derived4 : public derived3{//base的member不能被private继承的派生类的子类访问
public:
void fun(){
//std::cout<<a;
}
};
class derived5 : base{//默认private继承
void fun(){//derived class可以访问public和protected member
std::cout<<base::a<<base::b;
// std::cout<<base::c;//不能访问
}
};
int main(void)
{
base b1;
derived1 d1;
derived2 d2;
derived3 d3;
d1.fun();
d2.fun();
d3.fun();
std::cout<<b1.a;//base class Object只能访问public member
std::cout<<d1.a;//public继承时 derived class Object只能访问base class的public member
//std::cout<<d1.b<<d1.c;//不能访问
//std::cout<<d2.a<<d2.b;//protected继承时 derived class Object不能问访base class的member
//std::cout<<d3.a;//private继承时 derived class Object不能问访base class的member
return 0;
}