获取 C++ 中私有成员函数的函数指针

Getting function pointer of private member function in C++

本文关键字:函数 指针 成员 C++ 获取      更新时间:2023-10-16

有没有办法获取类内私有成员函数的函数指针

class A
{
public:
    void callMe()
    {
        cout<<__FUNCTION__<<endl;
    }
private:
    void fooMem()
    {
        cout<<__FUNCTION__<<endl;
    }
};
int _tmain(int argc, _TCHAR* argv[])
{
    auto fp = &A::fooMem;
    return 0;
}

在与 2012 c++ 编译器中编译它会导致以下错误

error C2248: 'A::fooMem' : cannot access private member declared in class 'A'
see declaration of 'A::fooMem'

研究了类似问题的惊人解决方案(尽管我不太清楚这实际上是如何工作的,如果有人可以解释这也很棒),在这里我希望成员的地址不要调用它。

我要求提供地址的原因是我将使用不同的实现修补此函数。

这样的类是不可修改的,但如果可以帮助实现这一目标,我可以继承。

由于您无法修改原始类,因此简单地继承该类并在公共成员空间中创建函数的副本会容易得多。

我尝试了这个,它按预期工作,至少在 g++ 中是这样:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class A
{
    public:
        void aFunction()
        {
            cout<<"This is aFunction"<<endl;
        }
    private:
        void anotherFunction()
        {
            cout<<"This is anotherFunction"<<endl;
        }
};
class B: public A
{
    public:
        void anotherFunction()
        {
            cout<<"This is also anotherFunction, but it's accessible!"<<endl;
        }
};
int main(int argc, char* argv[])
{
    A firstClass;
    B coach;
    firstClass.aFunction();
    coach.anotherFunction();
    return 0;
}

当我运行此代码时,我得到以下输出:

$ ./a.out
This is aFunction
This is also anotherFunction, but it's accessible!

证明编译器了解要使用另一个函数的版本。