C++ 继承方式

#include<iostream>
using namespace std;
class CFather
{
public:
    int m_nAge;
protected:
    int m_nSex;
private:
    int m_nName;
    CFather()
    {
        cout << m_nAge << endl;
        cout << m_nSex << endl;
        cout << m_nName << endl;
    }

};
//class CSon :public CFather//公有继承,基类中公有和保护不变;私有无法访问
//class CSon :protected CFather//保护继承,基类中公有和保护都变为保护继承;私有无法访问;
class CSon :private CFather//私有继承,基类中的公有和保护都变味私有;基类继承下来的私有还是无法访问;
{
public:
    CSon()
    {
        cout << m_nAge << endl;
        cout << m_nSex << endl;
        cout << m_nName << endl;
    }
};
class CSonSon :public CSon
{
public:
    CSonSon()
    {
        cout << m_nAge << endl;
        cout << m_nSex << endl;
        cout << m_nName << endl;
    }
};

int main()
{
    CSon son;
    //公有继承,只能在外部访问继承的公有,其他无法访问;、
    //保护继承,所有在外部的继承都不可访问;
    //私有继承,所有继承在外部都不可访问;
    son.m_nAge;
    son.m_nName;
    son.m_nSex;

    system("pause");
    return 0;
}

#include<iostream>

class Parent
{
public:
    Parent(int var = -1)
    {
     m_nPub = var; 
     m_nPtd = var;
     m_nPrt = var;
    }
public:
    int m_nPub;
protected:
    int m_nPtd;
private:
    int m_nPrt;
};
class Child1 : public Parent
{
public:
    int GetPub(){return m_nPub;};
    int GetPtd(){return m_nPtd;};
    int GetPrt(){return m_nPrt;};     //A           ERROR
};
class Child2 : protected Parent
{
public:
    int GetPub(){return m_nPub;};
    int GetPtd(){return m_nPtd;};
    int GetPrt(){return m_nPrt;};     //B           ERROR
};
class Child3 : private Parent
{
public:
    int GetPub(){return m_nPub;};
    int GetPtd(){return m_nPtd;};
    int GetPrt(){return m_nPrt;};     //C           ERROR
};

int main()
{
    Child1 cd1;
    Child2 cd2;
    Child3 cd3;

    int nVar = 0;

    //public inherited
    cd1.m_nPub = nVar;      //D         RIGHT
    cd1.m_nPtd = nVar;      //E         ERROR
    nVar = cd1.GetPtd();    //F         RIGHT
    //protected inherited       
    cd2.m_nPub = nVar;      //G         ERROR
    nVar = cd2.GetPtd();    //H         RIGHT
    //private inherited     
    cd3.m_nPub = nVar;      //I         ERROR
    nVar = cd3.GetPtd();    //J         RIGHT

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值