您的位置:首页 > 编程语言 > C语言/C++

C++的继承关系

2010-09-02 15:11 330 查看
#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: