Description
定义Person类,
1.有一个int类型属性age和1个char类型属性sex,分别为年龄和姓名。
2.构造函数和析构函数,输出如样例所示的信息。 定义Student类,是Person类的子类:
1.有一个int类型属性,是学生所在的班级号。
2.构造函数与析构函数,输出如样例所示的信息。 定义Teacher类,是Person类的子类:
1.有一个int类型属性,表示老师的工资。
2.构造函数与析构函数,输出如样例所示的信息。
Input
输入有多行,每行是一个测试用例。每行的第1个是一个正整数,是年龄;第2个是一个字符,表示性别;第3个是一个字符t或s,表示老师或学生;第4个是一个正整数,表示班号(对于学生)或工资(对于老师)。
Output
见样例。
Sample Input
18 f s 1
35 m t 8001
Sample Output
Person age = 18, sex = f is created.
Student of class 1 is created.
Student of class 1 is erased.
Person age = 18, sex = f is erased.
Person age = 35, sex = m is created.
Teacher with salary 8001 is created.
Teacher with salary 8001 is erased.
Person age = 35, sex = m is erased.
HINT
这里考察的是虚析构函数的知识点,main函数里面有new建立的对象。
Accepted Code (应该这么写)
/**
* 修改以前的题目
* 时间: 2020年6月4日21:39:33
*/
#include <iostream>
using namespace std;
class Person {
protected:
int age;
char sex;
public:
Person(int a , char s) : age(a), sex(s) {
cout << "Person age = " << age << ", sex = " << sex << " is created.\n";
}
//定义虚析构函数
virtual ~Person() {
cout << "Person age = " << age << ", sex = " << sex << " is erased.\n";
}
};
class Student : public Person {
protected:
int t1;
public:
Student(int a, char s, int t) : Person(a, s), t1(t) {
cout << "Student of class " << t1 << " is created.\n";
}
~Student() {
cout << "Student of class " << t1 << " is erased.\n";
}
};
class Teacher : public Person {
protected:
int par;
public:
Teacher(int a, char s, int p) : Person(a, s), par(p) {
cout << "Teacher with salary " << par << " is created.\n";
}
~Teacher() {
cout << "Teacher with salary " << par << " is erased.\n";
}
};
Append Code
int main()
{
Person *p;
int age, par;
char sex, t;
while (cin>>age>>sex>>t>>par)
{
if (t == 's')
{
p = new Student(age, sex, par);
}
else
{
p = new Teacher(age, sex, par);
}
delete p;
}
}
Accepted Code(奇怪的写法)
#include <iostream>
using namespace std;
class Person {
protected:
int age;
char sex;
public:
Person(int a , char s) : age(a), sex(s) {
cout << "Person age = " << age << ", sex = " << sex << " is created.\n";
}
~Person() {
cout << "Person age = " << age << ", sex = " << sex << " is erased.\n";
}
};
class Student : public Person {
protected:
int t1;
public:
Student(int a, char s, int t) : Person(a, s), t1(t) {
cout << "Student of class " << t1 << " is created.\n";
cout << "Student of class " << t1 << " is erased.\n";
}
~Student() {}
};
class Teacher : public Person {
protected:
int par;
public:
Teacher(int a, char s, int p) : Person(a, s), par(p) {
cout << "Teacher with salary " << par << " is created.\n";
cout << "Teacher with salary " << par << " is erased.\n";
}
~Teacher() {}
};