zoukankan      html  css  js  c++  java
  • c++继承实例

    #include <iostream>
    #include <vector>
    #include <string>
    using namespace std;
    
    class parent{
    protected:
        string pname;
    public:
        parent(string name){
            pname = name;
        }
        virtual void printname(){};
    
    };
    class child : public parent {
    protected:
        string cname;
    public:
        child(string name):parent(name){
            cname = name;
        }
        virtual void printname(){
            cout << "this is child, cname is" << cname << ", pname is " << pname << endl;
    
        }
    };
    class grandchild: public child{
    private:
        string gname;
    public:
        grandchild(string name):child(name){
            gname = name;
        }
        virtual void printname(){
            cout << "this is grandchild,gname is" << gname << ", cname is" << cname << ", pname is" << pname << endl;
        }
    };
    int main(){
        string name = "C";
        child Child(name);
        name = "GC";
        grandchild Gchild(name);
    
        vector<parent*> mlist;
        mlist.push_back(dynamic_cast<parent*>(&Child));
        mlist.push_back(dynamic_cast<parent*>(&Gchild));
    
        for(int i = 0; i < mlist.size(); i++){
            mlist[i] -> printname();
        }
        return 0;
    }

    结果:

  • 相关阅读:
    L1-031 到底是不是太胖了
    L1-030 一帮一
    PyCharm--git配置
    websocket--python
    UDP--python
    TCP--python
    pytest--metadata
    pytest--xdist
    pytest--夹具
    pytest--变量
  • 原文地址:https://www.cnblogs.com/simplepaul/p/7676174.html
Copyright © 2011-2022 走看看