这是一个关于定义一个基类——person类的问题,person类拥有姓名、性别、年龄等属性,再由基类派生出学生类——student类和教师类——teacher类。学生类新增加学号、班级、专业和入学成绩等属性,教师类新增加工号、职称和工资等属性。 c++代码
时间: 2023-10-28 13:04:31 浏览: 167
以下是C++代码实现:
```c++
#include <iostream>
#include <string>
using namespace std;
class Person {
protected:
string name;
char gender;
int age;
public:
Person(string name, char gender, int age) : name(name), gender(gender), age(age) {}
virtual void showInfo() {
cout << "Name: " << name << endl;
cout << "Gender: " << gender << endl;
cout << "Age: " << age << endl;
}
};
class Student : public Person {
private:
string studentID;
string className;
string major;
int entranceScore;
public:
Student(string name, char gender, int age, string studentID, string className, string major, int entranceScore) :
Person(name, gender, age), studentID(studentID), className(className), major(major), entranceScore(entranceScore) {}
void showInfo() {
cout << "Student Information:" << endl;
Person::showInfo();
cout << "Student ID: " << studentID << endl;
cout << "Class Name: " << className << endl;
cout << "Major: " << major << endl;
cout << "Entrance Score: " << entranceScore << endl;
}
};
class Teacher : public Person {
private:
string teacherID;
string title;
int salary;
public:
Teacher(string name, char gender, int age, string teacherID, string title, int salary) :
Person(name, gender, age), teacherID(teacherID), title(title), salary(salary) {}
void showInfo() {
cout << "Teacher Information:" << endl;
Person::showInfo();
cout << "Teacher ID: " << teacherID << endl;
cout << "Title: " << title << endl;
cout << "Salary: " << salary << endl;
}
};
int main() {
Person* person1 = new Student("Tom", 'M', 21, "20180001", "Class 1", "Computer Science", 90);
Person* person2 = new Teacher("Mary", 'F', 35, "10001", "Professor", 10000);
person1->showInfo();
person2->showInfo();
delete person1;
delete person2;
return 0;
}
```
解释如下:
- `Person`类是基类,拥有姓名、性别、年龄等属性,使用`virtual`关键字定义了虚函数`showInfo()`,可被子类重写。
- `Student`类和`Teacher`类分别继承自`Person`类。`Student`类新增加了学号、班级、专业和入学成绩等属性,`Teacher`类新增加了工号、职称和工资等属性。
- `showInfo()`函数在子类中被重写,可输出对应子类的信息。
- 在`main()`函数中创建了一个`Student`对象和一个`Teacher`对象,并使用基类指针`Person*`指向这两个对象。使用指针调用`showInfo()`函数时,会根据指针指向的具体对象类型调用对应的`showInfo()`函数。
- 由于使用了`new`关键字动态创建了对象,需要在程序结束时使用`delete`关键字释放内存。
阅读全文