什么类型的演员要从父母到孩子? [英] What Type of Cast to Go from Parent to Child?

查看:109
本文介绍了什么类型的演员要从父母到孩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是关于哪个 C ++风格的转换应该用于进行此转换。我知道一个C风格的转换可以实现这一点。

This question is about which C++ style cast should be used to make this conversion. I am aware that a C style cast can achieve this.

对于下面的结构:

class Foo {};

class Bar : public Foo {};

说给我: Foo * ptr; 我想把它转换为 Bar * 我应该使用哪种类型的转换?看起来我必须使用 dynamic_cast ,因为它是:

Say that I am given: Foo* ptr; and I want to cast it to a Bar* which type of cast should I be using? It seems like I must use dynamic_cast as it is:


用于转换多态类型

Used for conversion of polymorphic types

我想避免 dynamic_cast

推荐答案

您确定 dynamic_cast 通常是最适合这个情况。但是,如果您知道指针实际上指向派生类的对象,则可以使用 static_cast 进行转换。如果您错误,并且指针不是派生类,您将会得到未定义的行为。

You are correct that dynamic_cast is usually the most appropriate for this situation. However, if you know that the pointer is actually pointing to an object of the derived class, you can use static_cast for the conversion. If you're wrong and the pointer is not the derived class, you'll get undefined behavior.

这篇关于什么类型的演员要从父母到孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆