天天看點

Problem B: Person類與Student類的關系

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;
}