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;
}

结果:

 

posted @ 2017-10-16 11:29  爱简单的Paul  阅读(1423)  评论(0编辑  收藏  举报