C++ C++;:通过指针调用成员函数
我有一个使用指向成员函数的指针的示例代码,我想在运行时对其进行更改,但无法使其工作。我已经试过C++ C++;:通过指针调用成员函数,c++,function-pointers,C++,Function Pointers,我有一个使用指向成员函数的指针的示例代码,我想在运行时对其进行更改,但无法使其工作。我已经试过这个->*\u currentPtr(4,5)(*这个)。\u currentPtr(4,5)。在同一个类中调用指向方法的指针的正确方法是什么 错误:表达式必须具有(指向-)函数类型 #包括 #包括 甲级{ 公众: 无效设置PTR(int v); void useFoo(); 私人: typedef int(A::*fooPtr)(int A,int b); fooPtr_currentPtr; int
这个->*\u currentPtr(4,5)
(*这个)。\u currentPtr(4,5)
。在同一个类中调用指向方法的指针的正确方法是什么
错误:表达式必须具有(指向-)函数类型
#包括
#包括
甲级{
公众:
无效设置PTR(int v);
void useFoo();
私人:
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){
如果(v==1){
_currentPtr=foo1;
}否则{
_currentPtr=foo2;
}
}
void A::useFoo(){
//std::cout*_currentPtr(4,5);//错误
}
inta::foo1(inta,intb){
返回a-b;
}
inta::foo2(inta,intb){
返回a+b;
}
int main(){
obj;
目标设定值(1);
obj.useFoo();
返回0;
}
您需要告诉编译器foo
来自哪个类(否则它会认为它们是全局范围内的函数):
这里需要一组括号:
std::cout << (this->*_currentPtr)(4,5);
// ^ ^
std::cout*_currentPtr)(4,5);
// ^ ^
您收到的问题和错误消息是什么?谢谢您的帮助。但我不明白为什么需要&
运算符,我认为函数被视为地址。@ashur这对正常函数是正确的,但对成员函数不是。后者不是常规指针。@ashur请参阅有关成员指针的详细信息。
void A::setPtr(int v){
if(v == 1){
_currentPtr = &A::foo1;
// ^^^^
} else {
_currentPtr = &A::foo2;
// ^^^^
}
}
std::cout << (this->*_currentPtr)(4,5);
// ^ ^