为什么允许将派生类的方法静态广播到基类的方法? [英] Why is it allowed to static_cast a method of a derived class to a method of the base class?

查看:84
本文介绍了为什么允许将派生类的方法静态广播到基类的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例

struct B1{int x; void f(){x = 1;}};
struct D : B1{int x; void f(){B1::x = 2;}};

using Dmp = void(D::*)();
using B1mp = void(B1::*)();

int main()
{
    Dmp dmp = &D::f;
    D d;
    (d.*dmp)(); // ok

    B1mp b1mp = static_cast<B1mp>(dmp); // hm, well that's weird
    B1 b1;
    (b1.*b1mp)();

    dmp = &B1::f; // ok
}

此示例将编译并运行正常,并且不会出现任何问题.但是,等等,现在我要在D::f中使用D::x,现在-在运行时可能会发生任何事情.

And this example will compile and run just fine, and no problem will arise. But wait, now I'm going to use D::x in D::f, and now -- anything can happen at runtime.

是的,您还可以static_cast指向基数的指针到指向派生的指针.

Yes, you can also static_cast a pointer to the base to a pointer to a derived.

static_cast<D*>( (B1*)0 )

但是在这里,您可以使用RTTI来检查类型,或者在可能的情况下仅使用dynamic_cast.

But here you can use RTTI to check the types, or just use dynamic_cast if possible.

推荐答案

是的,static_cast允许许多可能以不安全"方式使用的东西,例如将void*转换为另一种对象指针类型,将Base*Derived*,还有这个.

Yes, static_cast allows a number of things that might be used in "unsafe" ways, like converting void* to another object pointer type, converting Base* to Derived*, and this one.

尽管与reinterpret_castconst_cast相比,static_cast可以被认为是相对安全的",但它仍然是强制转换.与所有强制类型转换一样,它表示要求忽略某些类型系统的安全要求,然后由程序员负责认真,正确地使用它.

Although static_cast can be thought of as "relatively safe" compared to reinterpret_cast and const_cast, it's still a cast. And like all casts, it represents a request to ignore some of the type system's safety requirements, with the programmer then responsible for using it carefully and correctly.

这篇关于为什么允许将派生类的方法静态广播到基类的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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