C++的继承关系

来源:互联网 发布:双色球关注数据采集 编辑:程序博客网 时间:2024/05/21 13:26

#include<iostream>
using namespace std;

class Parent
{
public:
    Parent(int var=0)
    {
        m_nPub=0;
        m_nPtd=0;
        m_nPrt=0;
    }
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;
    }
    */
};
class Child2:protected Parent
{
public:
    int getPub()
    {
        return m_nPub;
    }
    int getPtd()
    {
        return m_nPtd;
    }
    /*
    int getPrt()
    {
        return m_nPrt;
    }
    */
};
class Child3:private Parent
{
public:
    int getPub()
    {
        return m_nPub;
    }
    int getPtd()
    {
        return m_nPtd;
    }
    /*
    int getPrt()
    {
        return m_nPrt;
    }
    */
};


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

    int nVar=1;
    //public inherited
    cd1.m_nPub=nVar;
    //cd1.m_nPtd=nVar;
    //m_nPtd是基类Parent的protected成员变量,通过公有继承变成了
    //派生类Child1的Protected成员,因此只能在Child1内部访问,不能使用Child1对象访问.
    nVar=cd1.getPtd();
    //protected inherited
    //cd2.m_nPub=nVar;
    //Child2是protected继承,其基类的Parent的public和protected成员变量变成它的
    //protected成员,因此m_nPub只能在Child2类内部访问,不能使用Child2对象访问
    nVar=cd2.getPtd();
    //private inherited
    //cd3.m_nPub=nVar;
    //Child3是private继承,其基类的Parent的public和protected成员变量变成它的
    //private成员,因此m_nPub只能在Child3类内部访问,不能使用Child3对象访问
    nVar=cd3.getPtd();

    return 0;
}

原创粉丝点击