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;
这些演员表有什么问题?
What is wrong with these casts?
推荐答案
如何从点对象转换为子点对象?
How do I cast from a point object to a subpoint object?
你不能;除非 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.
您可以从 point
reference(或指针)转换为 subpoint
reference(或指针), 如果引用的对象实际上是 subpoint
类型:
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
不引用 subpoint
,则使用 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.
相关文章