指向成员函数的指针的向量 [英] Vector of pointer to member functions
问题描述
我正在尝试编写一个程序,该程序创建一个类,该类包含指向成员函数的指针的 vector ,并带有add()
和remove()
成员函数.
我写的代码是-
I'm trying to write a program which creates a class that contains vector of pointers to member functions, with add()
and remove()
member functions.
The code I wrote is -
1 #include <iostream>
2 #include <vector>
3 using namespace std;
4
5 typedef void(*classFuncPtr)();
6
7 class FunctionVectors
8 {
9 private:
10 vector<classFuncPtr> FunctionPointerVector;
11 public:
12 FunctionVectors(){}
13 void add(classFuncPtr funcPtr);
14 void remove(int index);
15 void run();
16 void a(){cout<<"a: Why are you calling me?"<<endl;}
17 };
18
19 void FunctionVectors::add(classFuncPtr funcPtr)
20 {
21 FunctionPointerVector.push_back(funcPtr);
22 }
23
24 void FunctionVectors::remove(int index)
25 {
26 FunctionPointerVector.erase(FunctionPointerVector.begin() + index);
27 }
28
29 int main()
30 {
31 FunctionVectors f;
32 classFuncPtr fv = &(classFuncPtr)FunctionVectors::a;
33
34 f.add(fv);
35 f.run();
36
37 return 0;
38 }
但是,它在第32行显示错误-
But, it is showing error in line# 32 -
error C2440: 'type cast' : cannot convert from 'void (__thiscall FunctionVectors::* )(void)' to 'classFuncPtr'
请告诉我如何修改它才能正常工作.
Please, tell me how should I modify it to work properly.
谢谢.
推荐答案
typedef void(*classFuncPtr)();
这不是方法的指针,而是函数的指针.方法与功能不同,因为方法是在上下文中调用的:要求this
才能正常工作.
This is not a pointer to method, but a pointer to function. Method differs from function, because it's being called in a context: requires this
to work correctly.
请记住,在C ++中,您只能创建指向特定类方法的指针向量.因此,您将无法在该向量中保留指向不同类的两个方法的指针.
Keep in mind, that in C++ you are only able to create vector of pointers to a method of specific class. So you won't be able to keep pointers to two methods of different classes in that vector.
解决方案(如注释中所建议的)是使用std::function
或boost::function
以及可能的C ++ 11 lambda,因为它们比简单的指向成员的指针提供了更多的灵活性.
The solution - as suggested in comments - is to use std::function
or boost::function
and possibly C++11 lambdas, because they provide a lot more flexibility than simple pointer-to-members.
如果要实现事件机制,请考虑也使用仿函数而不是方法:
If you want to implement an event mechanism, consider also using functors instead of methods:
-
为事件处理程序创建基类:
Create base class for event handler:
class MyEventHandler
{
public:
virtual void operator()(void * sender, int data) = 0;
}
创建这些的简单向量:
Create simple vector of these:
std::vector<MyEventHandler *> MyEvent;
在您的课程中创建特定的处理程序:
Create specific handlers in your classes:
class MyClass
{
private:
class SpecificEventHandler : MyEventHandler
{
public:
void operator()(void * sender, int data)
{
std::cout << "Event handled!";
}
}
public:
SpecificEventHandler Handler;
MyClass()
{
}
}
将处理程序挂接到您的事件:
Hook the handler to your event:
MyEvent.push_back(&(myClassInstance.Handler));
从内存写入的代码可能无法编译,但是您应该明白这一点.
Code written from memory, may not compile, but you should get the idea.
这篇关于指向成员函数的指针的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!