成员函数指针转换

member function pointer conversion

本文关键字:转换 指针 函数 成员      更新时间:2023-10-16
#include <iostream>
using namespace std;

class A {
};
typedef void (A::*funA)(int);
class B : public A {
public:
void m(int) {std::cout << "mm" << std::endl; }
void n(int) { std::cout << "nn"<<std::endl; }   
};
typedef void (B::*funB)(int);
class C : public B {
public:
void g(int) {std::cout << "gg" << std::endl; }
void h(int) { std::cout << "hh"<<std::endl; }
};
typedef void (C::*funC)(int);
int main() {
funB f = static_cast<funB>(&C::m);
A* pa = new A;
(pa->*(static_cast<funA>(f)))(2);
return 0;
}

GCC 编译并输出"mm"。但是为什么这能奏效呢?类 A 实际上没有定义任何函数。似乎该类可以通过这种方式使用其基类或派生类函数,即使它没有定义它们。

由于A不包含f引用的成员,因此行为是未定义的。

无论如何,它工作的可能原因是该函数B::m不接触this指针,因此当它被调用错误类型的对象时,它不会"注意到"。此外,AB 不是多态的,因此取消引用指向成员的指针和调用不需要检查任何 vptr。