c++继承和派生类问题

2024-12-28 05:03:25
推荐回答(2个)
回答1:

#include
#include
using namespace std;

class CPerson{
private:
string name;
char sex;//f-female,m-male
int age;
string work;
public:
CPerson(const string& name=string(),//类型后加小括号是赋个默认的初值
const char& sex=char(),
const int& age=int(),
const string& work=string()):name(name),
sex(sex),
age(age),
work(work){}
virtual ~CPerson(){};
void showName()const{
cout<<"Name:\t"< }
void showSex()const{
cout<<"Sex:\t"< }
void showAge()const{
cout<<"Age:\t"< }
void showWork()const{
cout<<"Work:\t"< }
virtual void showAllInfo()const{
showName();
showSex();
showAge();
showWork();
}
};
class CStudent : public CPerson{
string school;
string subject;
int grade;
public:
CStudent(const string& name=string(),
const char& sex=char(),
const int& age=int(),
const string& work=string(),
const string& school=string(),
const string& subject=string(),
const int& grade=int()
):CPerson(name,sex,age,work),school(school),
subject(subject),
grade(grade){}
void showSchool()const{
cout<<"School:\t"< }
void showSubject()const{
cout<<"Subject:"< }
void showGrade()const{
cout<<"Grade:\t"< }
void showAllInfo()const{
CPerson::showAllInfo();
showSchool();
showSubject();
showGrade();
}
};
int main()
{
CPerson cp("Green",'f',18,"teacher");
cp.showAllInfo();
cout<<"==================="< CStudent cs("Tom",'m',15,"student","Qinhua University","Math",2011);
cs.showAllInfo();

return 0;
}

回答2:

class Person{
string name;
bool gender;
int age;
string work;
public:
Person(string nam,bool gen,int age,string wor):name(nam),gender(gen),age(age),work(wor){}
void showname(){
cout<<"name:"< }
void showage(){
cout<<"age:"< }
void showgender(){
cout<<"gender:"<<(gender?"男":"女")< }
void showwork(){
cout<<"work"< }
void showall(){
cout<<"name:"< cout<<"age:"< cout<<"gender:"<<(gender?"男":"女")< cout<<"work"< }
};

class Student:public Person
{
string school;
string discipline;
int grade;
Student(string nam,bool gen,int age,string wor,string sch,strin dis,int gra):Person(nam, gen, age, wor),school(sch),discipline(dis),grade(gra){}
void showschool(){
cout<<"school"< }
void showzhuanye(){
cout<<"discipline"< }
void showgrade(){
cout<<"grade"< }
void showall(){
/*
cout<<"name:"< cout<<"age:"< cout<<"gender:"<<(gender?"男":"女")< cout<<"work"<*/
Person::showall()
cout<<"school"< cout<<"discipline:"< cout<<"grade"<
}

};