给定PersonFactory接口,要求实现该类,并以PersonFactory为父类派生学生(Student)与老师(Teacher)两个子类。学生有年级(int grade),老师有部门(char department[50])。基类的PrintInfo依次输出编号,姓名,年龄;学生的PrintInfo除了输出基类信息,还要输出年级;老师的PrintInfo除了输出基类信息,还要输出部门。各个输出项之间用回车换行符分隔。 基类如下: class PersonFactory { int id; char name[50]; int age; public: PersonFactory(int i = 0, char * nm = 0, int a = 15);//i:id;nm:name;a:age virtual ~PersonFactory() {}; virtual void PrintInfo() { cout << id << endl; cout << name << endl; cout << age << endl; }; PersonFactory * CreateStudent(int id, char *name, int age, int grade); PersonFactory * CreateTeacher(int id, char *name, int age, char *department); }; 其中构造函数、CreateStudent与CreateTeacher需要您完成函数定义。 Student与Teacher类需要您完成所有类的编写。 部分代码已给出,请将代码补充完整。
时间: 2023-06-15 17:07:04 浏览: 92
完整代码如下:
```c++
#include <iostream>
#include <cstring>
using namespace std;
class PersonFactory {
int id;
char name[50];
int age;
public:
PersonFactory(int i = 0, char * nm = 0, int a = 15) {
id = i;
strcpy(name, nm);
age = a;
}
virtual ~PersonFactory() {};
virtual void PrintInfo() {
cout << id << endl;
cout << name << endl;
cout << age << endl;
};
PersonFactory * CreateStudent(int id, char *name, int age, int grade);
PersonFactory * CreateTeacher(int id, char *name, int age, char *department);
};
class Student : public PersonFactory {
int grade;
public:
Student(int i, char *nm, int a, int g) : PersonFactory(i, nm, a) {
grade = g;
}
void PrintInfo() {
PersonFactory::PrintInfo();
cout << grade << endl;
}
};
class Teacher : public PersonFactory {
char department[50];
public:
Teacher(int i, char *nm, int a, char *dep) : PersonFactory(i, nm, a) {
strcpy(department, dep);
}
void PrintInfo() {
PersonFactory::PrintInfo();
cout << department << endl;
}
};
PersonFactory * PersonFactory::CreateStudent(int id, char *name, int age, int grade) {
return new Student(id, name, age, grade);
}
PersonFactory * PersonFactory::CreateTeacher(int id, char *name, int age, char *department) {
return new Teacher(id, name, age, department);
}
int main() {
PersonFactory *p1 = new Student(1, "Tom", 18, 3);
PersonFactory *p2 = new Teacher(2, "Jerry", 30, "Computer Science");
p1->PrintInfo();
p2->PrintInfo();
delete p1;
delete p2;
return 0;
}
```
其中,派生类的构造函数需要调用基类的构造函数来初始化成员变量,派生类的PrintInfo函数需要先调用基类的PrintInfo函数,再输出子类特有的信息。CreateStudent和CreateTeacher函数需要在类外定义,返回值为基类指针,指向派生类对象。在main函数中,分别创建学生和老师的对象,并调用PrintInfo函数输出信息,最后记得delete释放内存。
阅读全文