C++ 继承方式

来源:互联网 发布:异人启示录 知乎 编辑:程序博客网 时间:2024/05/13 05:17
#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;}
0 0
原创粉丝点击