码迷,mamicode.com
首页 > 编程语言 > 详细

c++继承实例

时间:2017-10-16 12:12:04      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:amp   cte   alt   str   rand   dynamic   ges   size   blog   

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

结果:

技术分享

 

c++继承实例

标签:amp   cte   alt   str   rand   dynamic   ges   size   blog   

原文地址:http://www.cnblogs.com/simplepaul/p/7676174.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!