获取 C++ 中私有成员函数的函数指针
Getting function pointer of private member function in C++
有没有办法获取类内私有成员函数的函数指针
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!
证明编译器了解要使用另一个函数的版本。
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针