在C ++中使用“ static_cast”进行向下转换 [英] Downcasting using the 'static_cast' in C++

查看:119
本文介绍了在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 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。 cv2 D ,其中 D 是从 B派生的类,如果存在从指针到 D 到指针到 B 的有效标准转换, cv2 cv1 B $ b具有相同的cv资格,或具有更高的cv资格$ b既不是 D 的虚拟基类,也不是 D 的虚拟基类的基类。空指针值将转换为目标类型的空指针值。如果类型指向 cv1 B 的指针的prvalue将
指向 B 实际上是 D 类型的对象的子对象,生成的指针指向 D类型的封闭对象
。否则,强制转换的结果是不确定的。

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天全站免登陆