Person類與Student類的關係
阿新 • • 發佈:2019-01-06
Description
當然,一個student首先是一個person。所以,Student類是Person類的派生類。請定義Person類,包括:
資料成員string name和int age,分別表示姓名和年齡。
建構函式和解構函式,它們有相應的輸出,見樣例。
void show()函式:按照樣例輸出該物件的name和age屬性值。
定義Student類,是Person類的子類:
資料成員int grade,表示學生所在年級。
建構函式和解構函式,它們有相應的輸出,見樣例。
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;
}
第二種方法在第一種方法的基礎上有一定的改進;
AC程式碼一
#include <iostream>
using namespace std;
class Person
{
private:
string name;
int age;
public:
Person():name("" ),age(0){}
Person(string na,int a):name(na),age(a){cout<<"A person "<<name<<" whose age is "<<age<<" is created."<<endl;}
void show(){cout<<"Name is "<<name<<" and age is "<<age<<"."<<endl;}
~Person(){cout<<"A person "<<name<<" whose age is "<<age<<" is erased."<<endl;}
};
class Student :public Person //無分號,這裡一定要注意;
{
private:
int grade;
public:
Student(string na,int a,int g):Person(na,a),grade(g){cout<<"A student whose grade is "<<grade<<" is created."<<endl;}
void show(){cout<<"Grade is "<<grade<<"."<<endl;}
~Student(){cout<<"A student whose grade is "<<grade<<" 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;
}
AC程式碼二
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Person
{
private:
string name;
int age;
public:
Person(string na="",int ag=0):name(na),age(ag){cout<<"A person "<<name<<" whose age is "<<age<<" is created."<<endl;}
void show(){cout<<"Name is "<<name<<" and age is "<<age<<"."<<endl;}
~Person(){cout<<"A person "<<name<<" whose age is "<<age<<" is erased."<<endl;}
};
class Student:public Person
{
private:
int grade;
public:
Student(string na="",int ag=0,int gr=0):Person(na,ag),grade(gr){cout<<"A student whose grade is "<<grade<<" is created."<<endl;}
void show(){cout<<"Grade is "<<grade<<"."<<endl;}
~Student(){cout<<"A student whose grade is "<<grade<<" 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;
}