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表示虚函数

猜你喜欢

转载自www.cnblogs.com/tsj816523/p/11070272.html