c++继承和派生类问题4
发布网友
发布时间:2024-02-28 20:13
我来回答
共2个回答
热心网友
时间:2024-07-22 14:06
#include <iostream>
#include <string>
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"<<name<<endl;
}
void showSex()const{
cout<<"Sex:\t"<<sex<<endl;
}
void showAge()const{
cout<<"Age:\t"<<age<<endl;
}
void showWork()const{
cout<<"Work:\t"<<work<<endl;
}
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"<<school<<endl;
}
void showSubject()const{
cout<<"Subject:"<<subject<<endl;
}
void showGrade()const{
cout<<"Grade:\t"<<grade<<endl;
}
void showAllInfo()const{
CPerson::showAllInfo();
showSchool();
showSubject();
showGrade();
}
};
int main()
{
CPerson cp("Green",'f',18,"teacher");
cp.showAllInfo();
cout<<"==================="<<endl;
CStudent cs("Tom",'m',15,"student","Qinhua University","Math",2011);
cs.showAllInfo();
return 0;
}
热心网友
时间:2024-07-22 14:06
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:"<<name<<endl;
}
void showage(){
cout<<"age:"<<age<<endl;
}
void showgender(){
cout<<"gender:"<<(gender?"男":"女")<<endl;
}
void showwork(){
cout<<"work"<<work<<endl;
}
void showall(){
cout<<"name:"<<name<<endl;
cout<<"age:"<<age<<endl;
cout<<"gender:"<<(gender?"男":"女")<<endl;
cout<<"work"<<work<<endl;
}
};
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"<<school<<endl;
}
void showzhuanye(){
cout<<"discipline"<<discipline<<endl;
}
void showgrade(){
cout<<"grade"<<grade<<endl;
}
void showall(){
/*
cout<<"name:"<<name<<endl;
cout<<"age:"<<age<<endl;
cout<<"gender:"<<(gender?"男":"女")<<endl;
cout<<"work"<<work<<endl;
*/
Person::showall()
cout<<"school"<<school<<endl;
cout<<"discipline:"<<discipline<<endl;
cout<<"grade"<<grade<<endl;
}
};