C ++继承向下转换 [英] C++ inheritance downcasting

查看:111
本文介绍了C ++继承向下转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的基本类如下:

class point    //concrete class
{
 ...    //implementation
}

class subpoint : public point  //concrete class
{
...     //implementation
}

如何从点对象投射到子点对象?我已经尝试了以下所有三个:

How do I cast from a point object to a subpoint object? I have tried all three of the following:

point a;
subpoint* b = dynamic_cast<subpoint*>(&a);
subpoint* b = (subpoint*)a;
subpoint b = (subpoint)a;

这些转换有什么问题?

推荐答案


如何从点对象转换为子对象?

How do I cast from a point object to a subpoint object?


$ b b

你不能;除非 point 有转换运算符,或 subpoint 有转换构造函数,在这种情况下,对象类型可以转换

You can't; unless either point has a conversion operator, or subpoint has a conversion constructor, in which case the object types can be converted with no need for a cast.

您可以从 或指针)到子点 引用(或指针),如果引用的对象实际上是 c $ c>:

You could cast from a point reference (or pointer) to a subpoint reference (or pointer), if the referred object were actually of type subpoint:

subpoint s;

point & a = s;
subpoint & b1 = static_cast<subpoint&>(a);
subpoint & b2 = dynamic_cast<subpoint&>(a);

第一个( static_cast )更危险;没有检查转换是否有效,因此如果 a 没有引用子点,那么使用 b1 将有未定义的行为。

The first (static_cast) is more dangerous; there is no check that the conversion is valid, so if a doesn't refer to a subpoint, then using b1 will have undefined behaviour.

第二个( dynamic_cast )更安全,但只有当 point 是多态的(即,如果它有一个虚函数)。如果 a 引用不兼容类型的对象,那么它将抛出异常。

The second (dynamic_cast) is safer, but will only work if point is polymorphic (that is, if it has a virtual function). If a refers to an object of incompatible type, then it will throw an exception.

这篇关于C ++继承向下转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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