Problem B: Person类与Student类的关系
原创
©著作权归作者所有:来自51CTO博客作者软糖酱八号机的原创作品,请联系作者获取转载授权,否则将追究法律责任
Problem B: Person类与Student类的关系
Description
当然,一个student首先是一个person。所以,Student类是Person类的派生类。请定义Person类,包括:
1. 数据成员string name和int age,分别表示姓名和年龄。
2. 构造函数和析构函数,它们有相应的输出,见样例。
3. void show()函数:按照样例输出该对象的name和age属性值。
定义Student类,是Person类的子类:
1. 数据成员int grade,表示学生所在年级。
2. 构造函数和析构函数,它们有相应的输出,见样例。
3. void show()函数:按照样例输出该对象的grade属性值。
Input
只有1行,分为三部分:一个不含空白符的字符串以及两个整数。
Output
见样例。
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
int age;
public:
Person(string s, int a) : name(s), age(a) {
cout << "A person " << name << " whose age is " << age << " is created." << endl;
}
~Person() {
cout << "A person " << name << " whose age is " << age << " is erased." << endl;
}
void show() {
cout << "Name is " << name << " and age is " << age << "." << endl;
}
};
class Student : public Person {
private:
int grade;
public:
Student(string s, int a, int g) : Person(s, a), grade(g) {
cout << "A student whose grade is " << grade << " is created." << endl;
}
~Student() {
cout << "A student whose grade is " << grade << " is erased." << endl;
}
void show() {
cout << "Grade is " << grade << "." << endl;
}
};
int main()
{
string n;
int a, g;
cin>>n>>a>>g;
Student student(n, a, g);
student.Person::show();
student.show();
return 0;
}