通過指向成員的指標訪問不存在的成員

當通過指向成員的指標訪問物件的非靜態成員時,如果該物件實際上不包含指標所表示的成員,則行為是未定義的。 (這樣的成員指標可以通過 static_cast 獲得。)

struct Base { int x; };
struct Derived : Base { int y; };
int Derived::*pdy = &Derived::y;
int Base::*pby = static_cast<int Base::*>(pdy);

Base* b1 = new Derived;
b1->*pby = 42; // ok; sets y in Derived object to 42
Base* b2 = new Base;
b2->*pby = 42; // undefined; there is no y member in Base