C++:通过指针调用成员函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16778498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++: Calling member function via pointer
提问by ashur
I have this example code of using pointer to member function, which I want to change during runtime, but I cannot make it work. I've already tried this->*_currentPtr(4,5)
(*this)._currentPtr(4, 5)
. What is the proper way of calling pointer to method inside same class ?
我有这个使用指向成员函数的指针的示例代码,我想在运行时更改它,但我无法让它工作。我已经试过了this->*_currentPtr(4,5)
(*this)._currentPtr(4, 5)
。在同一个类中调用指向方法的指针的正确方法是什么?
The error : expression must have (pointer-to-) function type
错误:表达式必须具有(指向)函数类型
#include <iostream>
#include <cstdlib>
class A {
public:
void setPtr(int v);
void useFoo();
private:
typedef int (A::*fooPtr)(int a, int b);
fooPtr _currentPtr;
int foo1(int a, int b);
int foo2(int a, int b);
};
void A::setPtr(int v){
if(v == 1){
_currentPtr = foo1;
} else {
_currentPtr = foo2;
}
}
void A::useFoo(){
//std::cout << this->*_currentPtr(4,5); // ERROR
}
int A::foo1(int a, int b){
return a - b;
}
int A::foo2(int a, int b){
return a + b;
}
int main(){
A obj;
obj.setPtr(1);
obj.useFoo();
return 0;
}
回答by jrok
You need to tell the compiler which class the foo
s are coming from (otherwise it thinks they're functions from global scope):
您需要告诉编译器foo
s 来自哪个类(否则它认为它们是全局范围内的函数):
void A::setPtr(int v){
if(v == 1){
_currentPtr = &A::foo1;
// ^^^^
} else {
_currentPtr = &A::foo2;
// ^^^^
}
}
and you need a set of parentheses here:
你需要一组括号:
std::cout << (this->*_currentPtr)(4,5);
// ^ ^