Problem D: Person類與Student類的關係 Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 623 Solved: 438
[ Submit][ Status][ Web Board]
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
見範例。
Sample Input
Tom 19 3
Sample Output
A person Tom whose age is 19 is created.A student whose grade is 3 is created.Name is Tom and age is 19.Grade is 3.A student whose grade is 3 is erased.A person Tom whose age is 19 is erased.
HINT
Append Code append.cc,
int main() { string n; int a, g; cin>>n>>a>>g; Student student(n, a, g); student.Person::show(); student.show(); return 0; }
代碼如下:
#include <iostream> #include <iomanip> #include <string> #include<cstring> using namespace std; class Person { public: string name; int age; public: Person(string _name,int _age) { name = _name; age = _age; 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 { public: int g; public: Student(string _name,int _age,int _g):Person(_name,_age) { g=_g; cout<<"A student whose grade is "<<g<<" is created."<<endl; } void show() { cout<<"Grade is "<<g<<"."<<endl; } ~Student() { cout<<"A student whose grade is "<<g<<" is erased."<<endl; } }; int main() { string n; int a, g; cin>>n>>a>>g; Student student(n, a, g); student.Person::show(); student.show(); return 0; }