C++习题-类02

来源:互联网 发布:布瑞克农业数据终端 编辑:程序博客网 时间:2024/05/12 19:33
/*
定义一个人员类CPerson, 姓名char cName[20]、编号int nNum、性别char cSex。
在此基础上派生出学生类CStudent(增加数据成员:成绩float fScore)
和教师类CTeacher(增加数据成员:教龄int  nSchoolAge)。
要求:
(1)基类和派生类均有带参的构造函数,能够对派生类中所有数据成员初始化;
(2)派生类中定义OutPut()函数,能够对派生类中所有数据成员值进行输出;
*/
#include <iostream>
#include <string.h>

using namespace std;

class CPerson{
    public:
        CPerson(){};
        CPerson(char name[],int n,char sex);
    protected:
        char cName[20];
        int  nNum;
        char cSex;
};
class CStudent:CPerson{
    public:
        CStudent(char *name,int n,char sex,float score);
        void OutPut();
    private:
        float fScore;
};
class CTeacher:CPerson{
    public:
        CTeacher(char *name,int n,char sex,int schoolage);
        void OutPut();
    private:
        int nSchoolAge;
};

int main()
{
    CStudent st1("小明",1001,'M',98);
    CTeacher tc1("李老师",0001,'W',10);
    st1.OutPut();
    cout << endl;
    tc1.OutPut();

    return 0;
}

CPerson::CPerson(char *name,int n,char sex){
    strcpy(cName,name);
    nNum=n;
    cSex=sex;
}

CStudent::CStudent(char *name,int n,char sex,float score):CPerson(name,n,sex){
    fScore=score;
}
void CStudent::OutPut(){
    cout << "姓名:" << cName << endl;
    cout << "编号:" << nNum << endl;
    cout << "性别:" << cSex << endl;
    cout << "成绩:" << fScore << endl;
}

CTeacher::CTeacher(char *name,int n,char sex,int schoolage):CPerson(name,n,sex){
    nSchoolAge=schoolage;
}
void CTeacher::OutPut(){
    cout << "姓名:" << cName << endl;
    cout << "编号:" << nNum << endl;
    cout << "性别:" << cSex << endl;
    cout << "教龄:" << nSchoolAge << endl;
}

原创粉丝点击