将子类转换为父类 [英] cast child class into parent class

查看:175
本文介绍了将子类转换为父类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这只是一个示例代码

 class parent{ //abstact class
        //pure virtual function
        virtual fun=0;
    }
    class child : parent{
        fun;
    }
    main()
    {
           //what should i do here,so i can add parent in vector
        attach(child);
    }
    void attach(parent* p){
        vector.push_back(p); //want to add reference of parent into vecotr
    }

推荐答案

子实例具有类型父级(和子级)。如果你有一个子实例,没有额外的父实例。您可以在需要父实例的任何位置使用子实例。没有必要施放。

The child instance has the type parent (and child). If you have an instance of child, there is no extra instance of parent lying around. You can use a child instance wherever a parent instance is required. There is no need to cast.

这篇关于将子类转换为父类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆