【问题标题】:cast child class into parent class将子类转换为父类
【发布时间】:2011-08-08 08:51:13
【问题描述】:

这只是一个示例代码

 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
    }

我想把孩子变成父母但不能 请任何人帮助我吗?

【问题讨论】:

    标签: oop class inheritance casting


    【解决方案1】:

    子实例具有 type 父(和子)。如果您有一个子实例,则周围没有额外的父实例。您可以在需要父实例的任何地方使用子实例。无需投射。

    【讨论】:

    • 非常感谢你,因为我犯了一个小错误,但你的回答解决了我的问题。
    【解决方案2】:
    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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多