派生到指向成员的指针的基本转换
可以使用 static_cast
将指向派生类成员的指针转换为指向基类成员的指针。指向的类型必须匹配。
如果操作数是指向成员值的空指针,则结果也是指向成员值的空指针。
否则,只有当操作数指向的成员实际存在于目标类中,或者目标类是包含操作数指向的成员的类的基类或派生类时,转换才有效。static_cast
不检查有效性。如果转换无效,则行为未定义。
struct A {};
struct B { int x; };
struct C : A, B { int y; double z; };
int B::*p1 = &B::x;
int C::*p2 = p1; // ok; implicit conversion
int B::*p3 = p2; // error
int B::*p4 = static_cast<int B::*>(p2); // ok; p4 is equal to p1
int A::*p5 = static_cast<int A::*>(p2); // undefined; p2 points to x, which is a member
// of the unrelated class B
double C::*p6 = &C::z;
double A::*p7 = static_cast<double A::*>(p6); // ok, even though A doesn't contain z
int A::*p8 = static_cast<int A::*>(p6); // error: types don't match