使用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 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 ++标准(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
是从code>,如果从指针
D
到指向B
的有效标准转换存在, cv2 与cv1 和B
$ b具有相同的cv- $ b既不是D
的虚拟基类,也不是D
的虚拟基类的基类。空指针值将转换为目标类型的空指针值。如果指向 cv1B
的类型的prvalue将
指向B
实际上是D
类型的对象的子对象,生成的指针指向类型D 的封闭对象
, code>。否则,投放的结果未定义。
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屋!