将子类转换为父类

时间:2011-08-08 08:51:14

标签: oop class inheritance casting

这只是一个示例代码

 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
    }

我希望将孩子投入父母,但不能 请做任何人帮助我吗?

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:0)

Class cast excetion :
 Occurs when u try to cast a parent class into child class.
 Reason: the parent class has not everything that a child class has, on the other hand a       child has everything that a parent has so you can cast a child into parent.
         In other words, the instance that you want to downcast  must be an instance of the class that to which you are downcasting.
相关问题