加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C多态性:从父类到子类

发布时间:2020-12-16 07:49:43 所属栏目:百科 来源:网络整理
导读:参见英文答案 When should static_cast,dynamic_cast,const_cast and reinterpret_cast be used?7个 在C中我们可以将子类指针转换为父类,但是有没有办法将它转换回来:从父类获得,从子类获得,给孩子类回来? 我的意思是: class Parent{ ...};class Child :
参见英文答案 > When should static_cast,dynamic_cast,const_cast and reinterpret_cast be used?7个
在C中我们可以将子类指针转换为父类,但是有没有办法将它转换回来:从父类获得,从子类获得,给孩子类回来?

我的意思是:

class Parent
{
    ...
};

class Child : public Parent
{
    ...
};

int main(int argc,char const *argv[])
{
    Child* child = new Child();
    Parent* parent = child;
    Child* old_child = parent; // how to do this??
    return 0;
}

谢谢您的回答.

解决方法

“but is there any way to convert it back: from parent,which was obtained from child,give child class back?”

是的,正如其他答案中所提到的,有两种方法可以做到这一点.

Child * old_child = dynamic_cast<Child*>(parent);

可以在运行时检查dynamic_cast<>的结果,因此您可以确定父对象是否真正表示Child实例:

if(!old_child) {
     // parent is not a Child instance
}

还要注意为了使其正常工作,所讨论的类需要有一个vtable,RTTI实际上可以确定它们的关系.实现此目的的最简单形式是为Parent类提供虚拟析构函数

class Parent {
public:
    virtual ~Parent() {}
    // or
    // virtual ~Parent() = default;
    // as suggested for latest standards
};

注意:
如果这应该适用于一般设计决定,我会强烈反对它.改为使用pure virtual interfaces,保证实现或不实现.

static_cast<>的第二种方式可以在环境中使用,在那里你很清楚父母实际上是一个孩子.最简单的形式是CRTP,其中Parent将继承类作为模板参数

template <class Derived>
class Parent {

     void someFunc() {
         static_cast<Derived*>(this)->doSomething();
     }
};

class Child : public Parent<Child> {
public:
    void doSomething();
};

父<>的实例化的有效性.和static_cast<>将在编译时检查.

注意:
另一个优点是你可以使用一个使用的派生接口

> Derived的静态类成员> typedef由Derived提供> …更多类特征,可以在编译时检查

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读