为什么允许将派生类的方法static_cast为基类的方法?

Why is it allowed to static_cast a method of a derived class to a method of the base class?

本文关键字:方法 cast 基类 static 派生 为什么      更新时间:2023-10-16

example

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,现在 - 任何事情都可能发生在运行时。

是的,您还可以static_cast指向基的指针指向派生的指针。

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

但是在这里你可以使用 RTTI 来检查类型,或者如果可能的话只使用dynamic_cast

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

虽然与reinterpret_castconst_cast相比,static_cast可以被认为是"相对安全"的,但它仍然是一个演员阵容。像所有强制转换一样,它表示忽略某些类型系统的安全要求的请求,然后程序员负责仔细正确地使用它。

in

void f(B *b) {
static_cast<D*>(b)->d_method();
b->static_cast<void (B::*)()>(&D::d_method)();
}

您假设b在每种情况下都是完全相同程度的D。 能够强制转换指向成员的指针允许调用方在传递给需要基的指针指向成员的函数时从任何派生类中指定任何函数。