公有继承和私有继承的实例

来源:互联网 发布:彻底删除苹果手机数据 编辑:程序博客网 时间:2024/04/30 07:52

#include "iostream.h"

#include "string.h"
class person //基类person定义
{
private:
char name[20];
int age;

bool sex;//0代表女,1代表男

public:

person() //基类构造函数

{
strcpy(name,"");
sex = 1;
age = 0;
}
person(char *strName,bool bSex,int nAge)//基类构造函数
{
setName(strName);
setSex(bSex);
setAge(nAge);
}
void setName(char *strName)//设置姓名
{
strcpy(name,strName);
}
void setSex(bool bSex)//设置性别
{
sex = bSex;
}
void setAge(int nAge)//设置年龄
{
age = nAge;
}
void display()//显示人员信息
{
cout<<"姓名为:"<<name<<endl;
cout<<"性别为:"<<(sex==1?"男":"女")<<endl;
cout<<"年龄为:"<<age<<endl;
}
};

class student : public person //派生类student定义,公有继承自基类person
{
private:
  char SID[20];
public:
student() //派生类student构造函数
{
strcpy(SID,"");  
}
student(char *strName,bool bSex,int nAge,char *strID)//派生类student构造函数
{
setName(strName);
setSex(bSex);
setAge(nAge);
setSID(strID);
}
void setSID(char *strID)//设置学号
{
strcpy(SID,strID);
}
void display()//显示学生信息
{
person::display();//显示继承自基类的基本信息
cout<<"学号:"<<SID<<endl;//显示student类独有的学号信息
}
};

void main()
{
  student s1("林燕",0,25,"0430900001"),s2; //分别调用两个构造函数,构造两个对象s1,s2。
  cout<<"调用s1.person::display()的输出为:"<<endl;
  s1.person::display(); //s1调用基类的display,输出结果
  cout<<"调用s1.display()的输出为:"<<endl;
  s1.display(); //s1调用派生类的display,输出结果
  cout<<"调用s2.display()的输出为:"<<endl;
  s2.display(); //s2调用派生类的display方法,输出结果为初始值
  s2.setName("王小明"); //对s2的姓名、性别、年龄、学号等进行设置
  s2.setAge(23);
  s2.setSex(1);
  s2.setSID("0430900002");
  cout<<"调用s2.display()的输出为:"<<endl;
  s2.display(); //再次输出s2的信息,为新设置的信息

}

/////以上如果换成是私有继承,则访问权限发生如下变化:

void main()
{
  student s1("林燕",0,25,"0430900001"),s2; //分别调用两个构造函数,构造两个对象s1,s2。
//  cout<<"调用s1.person::display()的输出为:"<<endl;
//  s1.person::display(); //s1调用基类的display,输出结果
  cout<<"调用s1.display()的输出为:"<<endl;
  s1.display(); //s1调用派生类的display,输出结果
  cout<<"调用s2.display()的输出为:"<<endl;
  s2.display(); //s2调用派生类的display方法,输出结果为初始值
//  s2.setName("王小明"); //对s2的姓名、性别、年龄、学号等进行设置
//  s2.setAge(23);
//  s2.setSex(1);
  s2.setSID("0430900002");
  cout<<"调用s2.display()的输出为:"<<endl;
  s2.display(); //再次输出s2的信息,为新设置的信息
}

//一个类中有三种类型的成员:private、protected和public 类型的成员,他们的区别是:

/*私有的只能在本类体中被用(不管是数据间的运算还是被成员函数使用);

保护的只能在本类体中或者在子类体中被用;

公有的可以在本类体中或者在子类体中,或者在类体外。

*/

//一个类的私有成员(通常是数据成员)是不能在该类的类外去访问的,只能在本类中的成员函数去访问,所以数据成员一般由类体里的成员函数去做形式上的赋值,然后具体生成对象时调用对象的函数来完成具体赋值,这时候就没有出现类的数据成员在类外被使用的情况,因为传递的是实参;

//这是因为公有继承时,基类的公有成员函数在派生类的访问权限不变,即还是子类的public成员,所以可以在子类的类外去访问它们;

//这是因为私有继承时,基类的公有成员函数在派生类的访问权限改变了,即父类的成员函数是子类的私有成员,不能子类的类外去访问它们。

0 0