C++ 如何在STL中调用函数指针
我很好奇如何在映射结构中调用函数指针。详情如下:C++ 如何在STL中调用函数指针,c++,stl,function-pointers,C++,Stl,Function Pointers,我很好奇如何在映射结构中调用函数指针。详情如下: #include<iostream> #include<map> #include<vector> #include<string.h> using namespace std; class FuncP; typedef int(FuncP::*func) (int, int); class FuncP { public: map<int, func> fmap; m
#include<iostream>
#include<map>
#include<vector>
#include<string.h>
using namespace std;
class FuncP;
typedef int(FuncP::*func) (int, int);
class FuncP
{
public:
map<int, func> fmap;
map<int, string> fstring;
public:
FuncP(){}
void initial();
int max(int x, int y);
int min(int x, int y);
int call(int op, int x, int y)
{
return (this->*fmap[op])(x, y);
}
};
void FuncP::initial()
{
fmap[0] = &FuncP::max;
fmap[1] = &FuncP::min;
fstring[0] = "fdsfaf";
}
int FuncP::min(int x, int y)
{
return (x<y)?x:y;
}
int FuncP::max(int x, int y)
{
return (x<y)?y:x;
}
int main()
{
func h = &FuncP::max;
FuncP *handle = new FuncP();
handle->initial();
cout<< handle->call(0, 1, 4); //1
cout<< (handle->FuncP::*fmap)[0](1,5); //2
return 0;
}
我不知道为什么会这样。1号和2号调用方法有什么区别?正如Piotr所评论的,正确的方法是
(handle->*(handle->fmap[0]))(1, 5);
说明:
handle->fmap[0]
提供函数指针。要调用它,需要取消对它的引用,给出*(handle->fmap[0])
(括号可选)
并在相关对象(句柄
)上调用它,留下上面的表达式
这基本上与您上面的语句
(This->*fmap[op])(x,y)
相同,只是handle->fmap[0]
而不是fmap[op]
,您没有包含std::string
的标题。请尝试以下操作:(handle->*handle->->fmap[0])(1,5)代码>或(*handle.*handle->fmap[0])(1,5)我知道了。但我仍然不明白其深层次的主旨。fmap已经是类中的公共变量。为什么我不能直接遵从fmap(即,(handle->*fmap[0])[1,5])?我明白了。但我仍然不明白其深层次的主旨。fmap已经是类中的公共变量。为什么我不能直接遵从fmap(即,(handle->*fmap[0])[1,5])?因为fmap引用的函数也可以在这个类的任何其他对象上调用:some-other-handle->*(handle->fmap[0])(1,5)
将导致some-other-handle->max(1,5)
。
(handle->*(handle->fmap[0]))(1, 5);