基类:
#include<iostream>
#include<string>
using namespace std;
class Person \\声明基类person
{
public:
Person() = default; \\默认构造函数
\\带参构造函数
Person(string Number, string Name) :number(Number), name(Name)
{
cout << "The contructor of base class Person is called." << endl;
}
void show()
{
cout << "The person's number:" << number << endl;
cout << "The person's name:" << name << endl;
}
~Person() = default; \\默认析构函数
protected: \\基类的保护数据成员
string number; \\编号
string name; \\姓名
};
学生类:
\\声明基类person的公用派生类student学生类
class Student :public Person
{
public:
Student() = default; \\默认构造函数
\\带参构造函数,在其初始化列表中调用基类的构造函数
Student(string Number, string Name, string Cnumber, float Result) :Person(Number, Name), cnumber(Cnumber), result(Result)
{
cout << "The constructor of derived class Student is classed." << endl;
}
void stushow()
{
cout << "学生的学号:" << number << endl;
cout << "学生的姓名:" << name << endl;
cout << "学生的班号:" << cnumber << endl;
cout << "学生的成绩:" << result << endl;
}
protected:
string cnumber; \\班号
float result; \\成绩
};
教师类:
\\声明基类person的公用派生类teacher教师类
class Teacher :public Person
{
public:
Teacher() = default; \\默认构造函数
\\带参构造函数,在其初始化列表中调用基类的构造函数
Teacher(string Number, string Name, string Title, string Section) :Person(Number, Name), title(Title), section(Section)
{
cout << "The constructor of derived class Student is classed." << endl;
}
void Teashow()
{
cout << "老师的编号:" << number << endl;
cout << "老师的姓名:" << name << endl;
cout << "老师的职称:" << title << endl;
cout << "老师所属的部门:" << section << endl;
}
protected:
string title; \\职称
string section; \\部门
};
主函数:
int main()
{
Student stu("000001", "张三", "01", 98);
stu.stushow(); \\显示学生信息
Teacher tea("000001", "李四", "教授", "人工智能");
tea.Teashow(); \\显示教师信息
system("pause");
return 0;
}
程序运行结果如下: