[英]Function pointer of a non-static member function of a class
I want to define a member function in class and use its pointer. 我想在类中定义一个成员函数并使用其指针。 I know that I can use static member function but the problem with it is that I can only access the static members of the class.
我知道我可以使用静态成员函数,但是它的问题是我只能访问该类的静态成员。 Is there a way other than static member function to be able to get function pointer.
除了静态成员函数以外,还有没有其他方法可以获取函数指针。
To be more specific: There is a library which I'm using which gets a function pointer as its input. 更具体地说:我正在使用一个库,它将函数指针作为输入。 I want to write a member function and assign its function pointer to that external library.
我想编写一个成员函数并将其函数指针分配给该外部库。 Should I create an object of class or use this pointer to do this?
我应该创建一个类的对象还是使用此指针来执行此操作?
You can get the pointer of the method, but it has to be called with an object 您可以获取该方法的指针,但是必须使用一个对象来调用它
typedef void (T::*MethodPtr) ();
MethodPtr method = &T::MethodA;
T *obj = new T();
obj->*method();
If you need to have non-object pointer and you want to use object then you have to store instance of object somewhere, but you are restricted to use only one object (singleton). 如果需要使用非对象指针,并且要使用对象,则必须将对象的实例存储在某个位置,但是只能使用一个对象(单例)。
class T {
static T *instance;
public:
T::T() {
instance = this;
}
static void func() {
instance->doStuff();
}
void doStuff() {}
};
If library supports user data for function pointers, then you may have multiple instances 如果库支持函数指针的用户数据,则您可能有多个实例
class T {
public:
static void func(void *instance) {
((T*)instance)->doStuff();
}
void doStuff() {}
};
Here is a complete sample program: 这是一个完整的示例程序:
#include <iostream>
class CTestFncPtr
{
public:
CTestFncPtr(int data) : mData(data)
{
// Switch = &CTestFncPtr::SwitchC; // Won't compile - wrong function prototype - this is type safe
if (data == 1)
Switch = &CTestFncPtr::SwitchA;
else
Switch = &CTestFncPtr::SwitchB;
}
void CallSwitch(char *charData)
{
(this->*Switch)(charData);
}
private:
void SwitchA(char * charData)
{
std::cout << "Called Switch A " << "Class Data is " << mData<<" Parameter is " << charData<< "\n";
Switch = &CTestFncPtr::SwitchB;
}
void SwitchB(char * charData)
{
std::cout << "Called Switch B " << "Class Data is " << mData<<" Parameter is " << charData<< "\n";
Switch = &CTestFncPtr::SwitchA;
}
void SwitchC()
{
}
void(CTestFncPtr::*Switch)(char * charData);
int mData;
};
int main(int argc, char * argv[])
{
CTestFncPtr item1(1);
item1.CallSwitch("Item1");
item1.CallSwitch("Switched call Item 1");
CTestFncPtr item2(0);
item2.CallSwitch("Item2");
item2.CallSwitch("Switched call Item 2");
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.