参见英文答案 >
When should static_cast,dynamic_cast,const_cast and reinterpret_cast be used?7个
在C中我们可以将子类指针转换为父类,但是有没有办法将它转换回来:从父类获得,从子类获得,给孩子类回来?
在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提供> …更多类特征,可以在编译时检查
原文地址:https://www.jb51.cc/c/115336.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。