2013-08-30 75 views
2

我正在将一个映射存储在一个类中,该类具有字符串作为键和指向成员函数的值作为值。我无法调用正确的函数抛出函数指针。 下面是代码:调用存储在std映射中的成员函数指针

#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; 
} 

在功能Preprocessor::processing如果字符串在地图上找到,那么,我所说的正常功能。问题是,在这个代码中,Preprocessor::take_new_key永远不会被调用。

错误在哪里?

谢谢

回答

6

正确的语法是这样的:

(this->*(result->second))(); 

这是丑陋的。所以让我们试试这个:

auto mem = result->second; //C++11 only 
(this->*mem)(); 

使用无论哪个让你开心。

+1

谢谢。这是正确的语法。 :) – Daniel

+0

我试图理解语法,我无法弄清楚为什么我不能写(*(result-> second))();你能为我提供一个答案吗?谢谢 – Daniel

+0

@Mike:要调用成员函数,需要一个对象。那么为什么'(*(result-> second))(); '会工作吗?成员被调用的对象在哪里? – Nawaz

2

result->second不调用函数指针。尝试((*this).*result->second)();