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;
};