Dan*_*iel 2 c++ stl function-pointers
我将地图存储在一个类中,该类具有字符串作为键和指向成员函数的指针作为值.我无法调用正确的函数抛出函数指针.这是代码:
#include <iostream>
#include <string>
#include <map>
using namespace std;
class Preprocessor;
typedef void (Preprocessor::*function)();
class Preprocessor
{
public:
Preprocessor();
~Preprocessor();
void processing(const string before_processing);
private:
void take_new_key();
map<string, function> srch_keys;
string after_processing;
};
Preprocessor::Preprocessor()
{
srch_keys.insert(pair<string, function>(string("#define"), &Preprocessor::take_new_key));
}
Preprocessor::~Preprocessor()
{
}
void Preprocessor::processing(const string before_processing)
{
map<string, function>::iterator result = srch_keys.find("#define");
if(result != srch_keys.end())
result->second;
}
void Preprocessor::take_new_key()
{
cout << "enters here";
}
int main()
{
Preprocessor pre;
pre.processing(string("...word #define other word"));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在函数中,Preprocessor::processing如果在地图中找到字符串,那么我调用正确的函数.问题是,在这段代码中,Preprocessor::take_new_key永远不会被调用.
哪里出错了?
谢谢
正确的语法是这样的:
(this->*(result->second))();
Run Code Online (Sandbox Code Playgroud)
那很难看.所以试试吧:
auto mem = result->second; //C++11 only
(this->*mem)();
Run Code Online (Sandbox Code Playgroud)
使用哪个让你开心.