C ++ dynamic_cast - 多态性要求和向下转换 [英] C++ dynamic_cast - polymorphic requirement and downcasting
问题描述
在下面的代码中,当 obj
在 case 1
中构建派生
类,但它的成员函数是不可访问的 obj
。因此,虽然下
铸造(即在情况2),使用 obj
作为源,我们任何如何构造的 code>中。为什么需要
obj
需要是多态的?
In the following code, while construction of obj
in case 1
we would any how construct derived
class too but it's member functions are just inaccessible to obj
. So while down-
casting ( i.e., in case 2 ) , using obj
as source, we any how has the constructed derived
in it. Why would it require obj
needs to be polymorphic?
如果我把你和上面的描述混淆, obj
不需要是多态的,但是当使用 dynamic_cast
时需要下载它。
If I confused you with my above description, Why in upcast obj
need not to be polymorphic but while downcast it needs to be while using dynamic_cast
?
class base
{
public:
base()
{
cout<< " \n base constructor \n";
}
};
class derived:public base
{
public:
derived()
{
cout <<" \n derived constructor \n";
}
};
base *obj = dynamic_cast<base*> (new derived) ; // case 1: explicitly upcasting
derived *OBJ = dynamic_cast<derived*> (obj) ; // case 2: error
谢谢。
推荐答案
从5.2.7 / 1 [expr.dynamic.cast]:
From 5.2.7/1 [expr.dynamic.cast] :
的表达式
dynamic_cast< T>(v)
是将表达式v转换为类型
T的结果。
The result of the expression
dynamic_cast<T>(v)
is the result of converting the expression v to type T.
[...]
如果T是指向 cv1 B的指针, cv2 D,使得B是D的基类,结果是指向由v指向的D对象的唯一B子对象的
指针。
If T is "pointer to cv1 B" and v has type "pointer to cv2 D" such that B is a base class of D, the result is a pointer to the unique B sub-object of the D object pointed to by v.
[...]
否则,v应是指向多态类型的指针或左值。
Otherwise, v shall be a pointer to or an lvalue of a polymorphic type.
标准甚至提供了以下示例,说明多态类型要求不代表派生到基本转换:
The standard even provides the following example which illustrates that the polymorphic type requirement does not stand for derived to base conversion :
struct B {};
struct D : B {};
void foo(D* dp)
{
B* bp = dynamic_cast<B*>(dp); // equivalent to B* bp = dp;
}
这篇关于C ++ dynamic_cast - 多态性要求和向下转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!