c++ 类的继承例子

Modified on: Mon, 08 Apr 2019 11:03:19 +0800 热度: 1,030 度
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

class Person{
protected:
    int No;
    char Name[20];
public:
    void input();
    void show();
};
class Stu:public Person{
private:
    int cls;
    int score;
public:
    void input();
    void show();
};
class Tea:public Person{
private:
    char zc[20];
    char dep[20];
public:
    void input();
    void show();
};

void Person::input()
{
    cout<<"姓名:";
    cin>>Name;
    cout<<"编号:";
    cin>>No;
}
void Stu::input()
{
    cout<<"请输入学生信息:"<<endl;
    Person::input();
    cout<<"班级:";
    cin>>cls;
    cout<<"成绩:";
    cin>>score;
}
void Tea::input()
{
    cout<<"请输入教师信息:"<<endl;
    Person::input();
    cout<<"职称:";
    cin>>zc;
    cout<<"部门:";
    cin>>dep;
}
void Person::show()
{
    cout<<"姓名:"<<Name<<endl;
    cout<<"编号:"<<No<<endl;
}
void Stu::show()
{
    cout<<"学生信息为:"<<endl;
    Person::show();
    cout<<"班级:"<<cls<<endl;
    cout<<"成绩:"<<score<<endl;
}
void Tea::show()
{
    cout<<"教师信息为:"<<endl;
    Person::show();
    cout<<"职称:"<<zc<<endl;
    cout<<"部门:"<<dep<<endl;
}
Stu stu[100];
Tea tea[100];
int main()
{
    cout<<"请输入需要执行的代码"<<endl;
    cout<<"1为增加教师,2为显示当前教师"<<endl;
    cout<<"3为增加学生,4为显示当前学生"<<endl;
    cout<<"0为退出程序"<<endl;
    int code;
    int i=0;
    int j=0;
    int n;
    while(1)
    {
        cout<<"code>";
        cin>>code;
        switch(code)
        {
        case 0:
            return 0;
        case 1:
            tea[i++].input();
            break;
        case 2:
            for(n=0;n<i;n++)
            {
                tea[n].show();
                cout<<"-----\n";
            }
            break;
        case 3:
            stu[j++].input();
            break;
        case 4:
            for(n=0;n<j;n++)
            {
                stu[n].show();
                cout<<"-----\n";
            }

            break;

        }
    }
    

    return 0;
}

添加新评论