c++访问控制与继承

来源:互联网 发布:linux is a directory 编辑:程序博客网 时间:2024/06/17 19:06

不考虑继承的话,我们可以认为一个类有两种不同的用户:普通用户类的实现者
普通用户编写的代码使用类的对象,这部分代码只能访问类的公有(接口)成员
实现者则负责编写类的成员和友元的代码,成员和友元既能访问 类的公有部分,也能访问类的私有(实现)部分

派生访问说明符对于派生类的成员(友元)能否访问其直接基类的成员没有影响,
对基类成员的访问权限只与基类中的访问说明符有关,
派生访问说明符的目的是控制派生类用户(包括派生类的派生类在内)对基类成员的访问权限

普通用户只能访问类的公有成员

普通用户对类的公有成员的访问还受到派生访问说明符的影响,即只能访问公有/继承的公有成员


//--------------------实现者的代码--------------------------class test{public:int pub_test;protected:int pro_test;private:int pri_test;};class pub_derv : public test{int p(){ return this->pro_test + this->pub_test; }//可以访问基类的公共和保护成员,不能访问私有成员friend int f(const pub_derv&);};class pro_derv : protected test{int p() { return this->pro_test + this->pub_test; }//可以访问基类的公共和保护成员,不能访问私有成员friend int f(const pub_derv&);};class pri_derv : private test{int p() { return this->pro_test + this->pub_test; }//可以访问基类的公共和保护成员,不能访问私有成员friend int f(const pub_derv&);};int f(const pub_derv &item){ return item.pub_test + item.pro_test; }//可以访问基类的公共和保护成员,不能访问私有成员//三个例子中都可以访问 pro_test, pub_test, 不能访问 pri_test//--①--->说明派生访问说明符对于派生类的成员(友元)能否访问其直接基类的成员没有影响,//对基类成员的访问权限只与基类中的访问说明符有关//派生访问说明符的目的是控制派生类用户(包括派生类的派生类在内)对基类成员的访问权限//--------------------普通用户的代码--------------------------int main(){test t;t.pub_test;/*t.pro_test; //错误,成员pro_test不可访问t.pri_test; //错误,成员pri_test不可访问*///--②--->上面的例子说明普通用户只能访问类的公有成员pub_derv pubd;pubd.pub_test;//pubd.pro_test; //错误,test::pro_test,无法访问protected成员//pubd.pri_test; //错误,test::pri_test,无法访问private成员pro_derv prod;//prod.pub_test; //错误,test::pub_test不可访问,因为 pro_derv使用protected从test继承pri_derv prid;//prid.pub_test; //错误,test::pub_test不可访问,因为 pri_derv使用private从test继承//--③--->上面的例子说明普通用户对类的公有成员的访问还受到派生访问说明符的影响,即只能访问公有继承的公有成员return 0;}

原创粉丝点击