【发布时间】:2020-04-01 08:42:13
【问题描述】:
例子
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。
【问题讨论】:
-
即使
D::f不使用任何其他D成员,程序也有未定义的行为。写b1.*b1mp获取对象中不存在的成员是无效的,不管该成员的定义是什么。
标签: c++ methods language-lawyer function-pointers static-cast