我想要创建一个指向方法的指针数组,这样我就可以根据一个整数快速地选择要调用的方法。但我对语法有点纠结。
我现在拥有的是:
class Foo {
private:
void method1();
void method2();
void method3();
void(Foo::*display_functions[3])() = {
Foo::method1,
Foo::method2,
Foo::method3
};
};但我得到以下错误消息:
[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发布于 2022-11-27 15:52:18
是的,你可以,你只需要记下他们的地址:
void(Foo::*display_functions[3])() = {
&Foo::method1,
&Foo::method2,
&Foo::method3
};..。但是,如果有一个接口的virtual方法,或者一个简单的方法,将它们全部调用为多方法模式,可能会更好。
发布于 2022-11-27 15:55:55
可以对指向方法的指针类型使用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
};
};您也可以使用一个typedef语句来代替using语句:
using FooMemFn = void (Foo::*)();请注意,必须将operator&与类方法结合使用才能获得指针到方法。
附带注意:如果display_functions在不同的类实例之间不发生变化,可以考虑使它保持静态。
https://stackoverflow.com/questions/74591455
复制相似问题