#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);//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); }; int main() { PersonFactory vn; PersonFactory *ps,*pt; int id,age,grade; char name[50],department[50]; cin>>id>>name>>age>>department; ps=vn.CreateTeacher (id,name,age,department); ps->PrintInfo (); cin>>id>>name>>age>>grade; ps=vn.CreateStudent (id,name,age,grade); ps->PrintInfo (); return 0; }请依据这段代码,将其补全完成上个问题将上个问题
时间: 2023-06-15 18:06:47 浏览: 119
以下是补全后的代码:
```
#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;
};
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 *dp) : PersonFactory(i, nm, a)
{
strcpy(department, dp);
}
void PrintInfo()
{
PersonFactory::PrintInfo();
cout << department << endl;
}
};
PersonFactory * CreateStudent(int id, char *name, int age, int grade)
{
return new Student(id, name, age, grade);
}
PersonFactory * CreateTeacher(int id, char *name, int age, char *department)
{
return new Teacher(id, name, age, department);
}
};
int main()
{
PersonFactory vn;
PersonFactory *ps,*pt;
int id,age,grade;
char name[50],department[50];
cin>>id>>name>>age>>department;
pt=vn.CreateTeacher (id,name,age,department);
pt->PrintInfo ();
cin>>id>>name>>age>>grade;
ps=vn.CreateStudent (id,name,age,grade);
ps->PrintInfo ();
return 0;
}
```
这个程序使用了工厂模式,其中 PersonFactory 类是一个抽象基类,包含了一个虚函数 PrintInfo(),用于打印人员的信息。它有两个派生类,分别是 Student 和 Teacher,分别表示学生和教师。在 PersonFactory 类中,定义了两个工厂方法 CreateStudent() 和 CreateTeacher(),用于创建学生和教师对象。在 main() 函数中,首先调用 CreateTeacher() 方法创建一个教师对象,然后调用 PrintInfo() 方法打印出教师的信息;接着调用 CreateStudent() 方法创建一个学生对象,然后调用 PrintInfo() 方法打印出学生的信息。
阅读全文