派生类的指针可以类型转换为其基类的指针吗? [英] Can a pointer of a derived class be type cast to the pointer of its base class?

查看:387
本文介绍了派生类的指针可以类型转换为其基类的指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

new返回的派生类的指针可以类型转换为其基类的指针。

The pointer of derived class returned by new can be type cast to the pointer of its base class.

这是真还是假?

我知道dynamic_cast可以用来投下。一般来说,如何将派生类的指针转换为其基类的指针?

I know dynamic_cast can be used to cast downside. Generally, how to cast a pointer of derived class to a pointer of its base class?

推荐答案

是的。从指针到派生类到指向基类的指针的转换是隐式的。因此,以下是完全正确的:

Yes. Conversion from a pointer to a derived class to a pointer to a base class is implicit. Thus, the following is perfectly fine:

struct B { };
struct D : B { };

D* my_d_ptr = new D;
B* my_d_ptr_as_a_b_ptr = my_d_ptr;

这篇关于派生类的指针可以类型转换为其基类的指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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