C++练习 | 类的继承与派生练习(1)

#include <iostream>
#include <cmath>
#include <cstring>
#include <string>
#include <iomanip>
#include <algorithm>
#include <stack>
#include <fstream>
#include <map>
#include <vector>
using namespace std;

class Person
{
protected:
    string name;
    int age;
public:
    Person()
    {
        
    }
    virtual ~Person()
    {
        
    }
    virtual void input()
    {
        cin>>name>>age;
    }
    virtual void show()
    {
        cout<<name<<" "<<age<<endl;
    }
};

class Student:public Person
{
private:
    int num;
public:
    Student()
    {
        
    }
    void input()
    {
        cin>>name>>age>>num;
    }
    void show()
    {
        cout<<name<<" "<<age<<" "<<num<<endl;
    }
    ~Student()
    {
        
    }
};

class Teacher:public Person
{
private:
    string zc;
public:
    Teacher()
    {
        
    }
    void input()
    {
        cin>>name>>age>>zc;
    }
    void show()
    {
        cout<<name<<" "<<age<<" "<<zc<<endl;
    }
    ~Teacher()
    {
        
    }
};

void work(Person *p)
{
    p->input();
    p->show();
    delete p;
}

int main() {
    char c;
    while (cin >> c)
    {
        switch (c)
        {
            case 'p':
                work(new Person());
                break;
            case 's':
                work(new Student());
                break;
            case 't':
                work(new Teacher());
                break;
            default:
                break;
        }
    }
    return 0;
}

new调用构造函数,delete调用虚构函数

virtual表示虚函数

posted @ 2019-06-22 20:40  洛枫大人  阅读(522)  评论(0编辑  收藏  举报