[英]How can I make an array of method pointers?
I want to create an array of pointers to methods, so I can quickly select a method to call, based on a integer. But I am struggling a little with the syntax.我想创建一个指向方法的指针数组,这样我就可以快速 select 调用一个基于 integer 的方法。但是我在语法上遇到了一些困难。
What I have now is this:我现在拥有的是:
class Foo {
private:
void method1();
void method2();
void method3();
void(Foo::*display_functions[3])() = {
Foo::method1,
Foo::method2,
Foo::method3
};
};
But I get the following error message:但我收到以下错误消息:
[bf@localhost method]$ make test
g++ test.cpp -o test
test.cpp:11:9: error: cannot convert ‘Foo::method1’ from type ‘void (Foo::)()’ to type ‘void (Foo::*)()’
11 | };
| ^
test.cpp:11:9: error: cannot convert ‘Foo::method2’ from type ‘void (Foo::)()’ to type ‘void (Foo::*)()’
test.cpp:11:9: error: cannot convert ‘Foo::method3’ from type ‘void (Foo::)()’ to type ‘void (Foo::*)()’
make: *** [<builtin>: test] Error 1
Yes, you can, you just need to take the address of them:是的,你可以,你只需要获取他们的地址:
void(Foo::*display_functions[3])() = {
&Foo::method1,
&Foo::method2,
&Foo::method3
};
... however, it's likely better if you have virtual
methods for an interface or a simple method that calls them all for a multi-method pattern. ...但是,如果您有接口的virtual
方法或为多方法模式调用所有方法的简单方法,可能会更好。
You can use typedef
for the type of pointer to your methods, and then store your methods in a std::array
holding that type:您可以使用typedef
作为指向您的方法的指针类型,然后将您的方法存储在包含该类型的std::array
中:
class Foo {
private:
void method1() {};
void method2() {};
void method3() {};
typedef void (Foo::* FooMemFn)();
std::array<FooMemFn,3> display_functions = {
&Foo::method1,
&Foo::method2,
&Foo::method3
};
};
Instead of typedef
you can also use a using
statement:除了typedef
,您还可以使用using
语句:
using FooMemFn = void (Foo::*)();
Note that you must use operator&
with a class method to obtain a pointer-to-method.请注意,您必须将operator&
与 class 方法一起使用以获得指向方法的指针。
A side note: consider to make display_functions
static if it will not change between various class instances.旁注:如果display_functions
static 不会在各种 class 实例之间发生变化,请考虑制作它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.