C dynamic_cast – 多态需求和向下转换
作者:互联网
在下面的代码中,在构造案例1中的obj时,我们也构造了一个派生类对象,但它的成员函数对于obj是不可访问的.因此,在向下转换(即,在情况2中)时,使用obj作为源,我们已经在其中导出了所构造的构造.为什么obj需要是多态的?
如果我把我与上面的描述混淆了,为什么在向上转换时obj不需要是多态的,但是在使用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]:
The result of the expression
dynamic_cast<T>(v)
is the result of converting the expression v to type
T.[…]
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.[…]
Otherwise, v shall be a pointer to or an lvalue of a polymorphic type.
该标准甚至提供了以下示例,该示例说明多态类型要求不代表派生到基本转换:
struct B {};
struct D : B {};
void foo(D* dp)
{
B* bp = dynamic_cast<B*>(dp); // equivalent to B* bp = dp;
}
标签:downcast,dynamic-cast,c 来源: https://codeday.me/bug/20191005/1857893.html