protected private public访问

1、类成员函数可以访问类内:private+protected+public
2、类对象可以访问类内: public (protected+private不可)
3、派生类成员函数可以访问父类内:protected+public (private不可)
4、派生类对象可以访问: public (protected+private不可)
5、总结:private和protected类之间的区别只有在基类派生的类中才会体现出来,派生类的成员可以直接访问基类的protected成员,但不能直接访问基类的private成员。对于外部世界,protected成员与private成员相似;对派生类来说,protected成员与public成员相似。
6、各类派生例程:

#include <iostream>
using namespace std;

class Base{
private:
    int a1;
protected:
    int a2;
public:
    int a3;
    Base()
    {
        a1=1;a2=2;a3=3;
    }
};

class child1 : public Base
{
public:
    child1():Base(){}
    void func()
    {
        //cout << a1 << endl;   //private   wrong!
        cout << a2 << endl;     //protected
        cout << a3 << endl;     //public
    }
};

class child2 : protected Base
{
public:
    child2():Base(){}
    void func()
    {
        //cout << a1 << endl;   //private   wrong!
        cout << a2 << endl;     //protected
        cout << a3 << endl;     //protected
    }
};

class child3 : private Base
{
public:
    child3():Base(){}
    void func()
    {
        //cout << a1 << endl;   //private   wrong!
        cout << a2 << endl;     //private ,can be used by child class
        cout << a3 << endl;     //private ,can be used by child class
    }
};

int main()
{
    child1 child;
    //cout << child.a1 << endl;   //private
    //cout << child.a2 << endl;   //protected  wrong!
    cout << child.a3 << endl;     //public

    child2 _child;
    //cout << _child.a1 << endl;   //private
    //cout << _child.a2 << endl;   //protected  wrong!
    //cout << _child.a3 << endl;   //protected  wrong!

    child3 __child;
    //cout << __child.a1 << endl;   //private
    //cout << __child.a2 << endl;   //private  wrong!
    //cout << __child.a3 << endl;   //private  wrong!

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值