我对C++非常陌生(在许多Java年之后)。我试图使用指向类成员函数的函数指针如下:
class MyClass
{
public:
MyClass();
void foo();
void bar();
};
MyClass::MyClass(){}
void MyClass::bar(){}
void MyClass::foo()
{
void (MyClass::*myMethod)();
myMethod = &MyClass::bar;
//-----THIS IS THE LINE WITH PROBLEM-----------
myMethod();
}但是,编译器失败:
test.cpp: In member function ‘void MyClass::foo()’:
test.cpp:22:14: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘myMethod (...)’, e.g. ‘(... ->* myMethod) (...)’
myMethod();
^我已经尝试了各种混合的*,&字符,谷歌搜索解决方案,但无法使它发挥作用。
有什么想法吗?
发布于 2015-10-08 10:34:33
myMethod是一个成员函数,因此您需要在它所属的类的实例上调用它。由于您已经在成员函数中,所以可以使用this。
(this->*myMethod)()https://stackoverflow.com/questions/33013248
复制相似问题