zoukankan      html  css  js  c++  java
  • 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表示虚函数

  • 相关阅读:
    软件工程——小学生的四则运算(java)
    软件工程——小学生的四则运算
    利用python实现微信小项目
    SQLite3数据库
    爬虫———python
    模拟足球训练
    文件的转换
    学习成绩雷达图
    <dvi>
    vue 锚点跳转防止路径变化后,刷新页面报错的问题
  • 原文地址:https://www.cnblogs.com/tsj816523/p/11070272.html
Copyright © 2011-2022 走看看