使用C ++中的Static_cast进行下转换 [英] Downcasting using the Static_cast in C++

查看:247
本文介绍了使用C ++中的Static_cast进行下转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

A prvalue of type "pointer to cv1 B", where B is a class type, can be converted to a prvalue of type "pointer to cv2 D", where D is a class derived from B, if a valid standard conversion from "pointer to D" to "pointer to B" exists, cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is neither a virtual base class of D nor a base class of a virtual base class of D. The null pointer value is converted to the null pointer value of the destination type. If the prvalue of type "pointer to cv1 B" points to a B that is actually a subobject of an object of type D, the resulting pointer points to the enclosing object of type D. Otherwise, the result of the cast is undefined.

这篇关于使用C ++中的Static_cast进行下转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆