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

  • 相关阅读:
    面试问题
    知识点整合
    前端错误
    基于.NET平台常用的框架整理
    BFC和haslayout
    javascript面向对象
    javascript变量的作用域
    2014-05-26 总结
    2014-05-23 总结
    PHP实现mvc模式的思想
  • 原文地址:https://www.cnblogs.com/tsj816523/p/11070272.html
Copyright © 2011-2022 走看看