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;
}
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;
}
相关文章推荐
- 浅析C++中的is-a和has-a关系(公有继承、包含、私有继承)
- C++ 类的继承关系,及访问权限
- C++ 中结构体的继承关系
- c++ 覆盖 隐藏以及一些继承的关系
- c++ 继承关系的构造函数
- C++继承关系中Data Member和Functions Member的内存布局(基于C++ Object Model描述)
- C++中的三种继承关系
- python之自动生成C++的父子双向继承关系
- 读书笔记_Effective_C++_条款三十二:确定你的public继承继承塑模出is-a关系
- 【c++】深入剖析虚拟继承与各种继承关系中派生类内成员内存分布情况及虚基类表的内容
- Java与C++区别之继承关系中的函数
- c++的继承关系和函数重载
- C++继承中成员变量关系及访问方法的深入探究
- C++中三个特性(继承、封装、多态、类之间的关系)
- Thinking in C++: 第1章 继承:类型关系
- C++私有继承实现has-a关系
- c++ 友元关系与继承
- C++继承关系
- C++继承关系
- c++ 友元关系与继承