C多态性:从父类到子类

C多态性:从父类到子类,第1张

概述参见英文答案 > When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?                                    7个 在C中我们可以将子类指针转换为父类,但是有没有办法将它转换回来:从父类获得,从子类获得,给孩子类回来? 我的意思是: class Parent{ 参见英文答案 > 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提供> …更多类特征,可以在编译时检查

总结

以上是内存溢出为你收集整理的C多态性:从父类到子类全部内容,希望文章能够帮你解决C多态性:从父类到子类所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1232716.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存