在C ++中使用“ static_cast”进行向下转换 [英] Downcasting using the 'static_cast' in C++
问题描述
考虑:
class base
{
base();
virtual void func();
}
class derived : public base
{
derived();
void func();
void func_d();
int a;
}
main
{
base *b = new base();
sizeof(*b); // Gives 4.
derived * d = static_cast<derived*>(b);
sizeof(*d); // Gives 8- means whole derived obj size..why?
d->func_d();
}
在上面的代码中,我对指向基础对象的基础指针做了向下转换派生类指针。我想知道派生指针如何具有整个派生类对象。我可以调用派生类函数(仅在派生类中声明)。
In the above code I did downcasting of a base pointer which points to base object to derived class pointer. I am wondering how the derived pointer has the whole derived class object. I can call the derived class function (declared in derived class only). I did not get the concept here.
推荐答案
使用 static_cast
进行投射类型实际上不具有未定义行为的对象。 UB的症状差异很大。没有什么说UB不能成功地调用派生成员函数(但是没有任何东西可以保证它会成功调用,所以不要指望它)。
Using static_cast
to cast an object to a type it doesn't actually have yields undefined behavior. The symptoms of UB vary widely. There's nothing that says UB can't allow the derived member function to be called successfully (but there's nothing that guarantees that it will, so don't count on it).
以下是使用 static_cast
进行向下转换的规则,请参见第5.2.9节( [expr.static.cast]
)(C ++ 0x措辞):
Here is the rule for downcasting using static_cast
, found in section 5.2.9 ([expr.static.cast]
) of the C++ standard (C++0x wording):
类型为指向 cv1 的指针的prvalue
B
,其中B
是类类型,可以转换为指向的指针类型的prvalue。 cv2D
,其中D
是从B派生的类
,如果存在从指针到D
到指针到B
的有效标准转换, cv2 与 cv1 和B
$ b具有相同的cv资格,或具有更高的cv资格$ b既不是D
的虚拟基类,也不是D
的虚拟基类的基类。空指针值将转换为目标类型的空指针值。如果类型指向 cv1B
的指针的prvalue将
指向B
实际上是D
类型的对象的子对象,生成的指针指向D类型的封闭对象
。否则,强制转换的结果是不确定的。
A prvalue of type "pointer to cv1
B
", whereB
is a class type, can be converted to a prvalue of type "pointer to cv2D
", whereD
is a class derived fromB
, if a valid standard conversion from "pointer toD
" to "pointer toB
" exists, cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, andB
is neither a virtual base class ofD
nor a base class of a virtual base class ofD
. The null pointer value is converted to the null pointer value of the destination type. If the prvalue of type "pointer to cv1B
" points to aB
that is actually a subobject of an object of typeD
, the resulting pointer points to the enclosing object of typeD
. Otherwise, the result of the cast is undefined.
这篇关于在C ++中使用“ static_cast”进行向下转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!