C语言中 继承与派生

C语言中的继承与派生中 观察下面代码 Class是一个类。继承就是在已经纯在的类的基础上建立了一个新的类。一个新的类从之前的类中获得了已有的体型,这种现象称为类的继承,通过继承就可以新建子类从已有的父类那里获得父类的特性,这时候Class就是一个父类 而下面的teacher 和 student 是它的子类。从父类中产生一个新的子类 ,这就称为类的派生。没一个派生类又可以作为基类再派生出新的派生类。因此类和派生类是相对的。

#include<iostream>
#include<string>
using namespace std;

class Preson
{ //全参构造函数
  public:
  Preson(string name, string sex)
 {
  this->name = name;
  this->sex = sex;
 }
 void display(){
  cout << "name:" << name << endl;
  cout << "sex:" << sex << endl;
 };
 private:
 //名字
 string name;
 //性别
 string sex;
};
class teacher :public Preson   //派生类的的声明方式
{

private:
 int num;                      //新增加的数据成员 (私有)
 int money;
public:
 teacher(int num, int money, string name, string sex):Preson(name, sex){
  this->num = num;
  this->money = money;
 }
 void display(){
  cout << "工号:" << num << endl;
  Preson::display();
  cout << "薪资:" << money << endl;
 };
 void teach(){
  cout << """教书 育人""" << endl;
 };
 void check(){
  cout << """作业的检测""" << endl;
 };
};
class student :public Preson
{
private:
 int num;
 int score;
public:
 student(int num, int score, string name, string sex):Preson(name, sex){
  this->num = num;
  this->score = score;
 }
 void display(){
  cout << "学号:" << num << endl;
  Preson::display();
  cout << "分数:" << score << endl;
 };
 void study(){
  cout << "好好学习,天天向上" << endl;
 };
 void test(){
  cout << "认真完成" << endl;
 };

 
};
int main(){
 Preson pres = Preson("张三", "男");
 pres.display();
 cout << "**************************" << endl;
 teacher tech = teacher(1034, 4000, "李四", "男");
 tech.display();
 tech.check();
 tech.teach();
 cout << "***************************" << endl;
 student stu = student(45,66,"王五", "男" );
 stu.display();
 stu.study();
 stu.test();
 cout << "***************************" << endl;
 teacher cl = teacher(1037, 3000, "马六", "女");
 cl.display();
 cout << "***************************" << endl;
 student st = student(44, 80, "宋七", "男");
 st.display();
 return 0;
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值