【问题标题】:Calling a member function pointer stored in a std map调用存储在标准映射中的成员函数指针
【发布时间】:2013-08-30 15:06:14
【问题描述】:

我将一个映射存储在一个类中,该类将字符串作为键,将成员函数的指针作为值。我在调用正确的函数时遇到问题,抛出函数指针。 代码如下:

#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 从未被调用过。

错在哪里?

谢谢

【问题讨论】:

    标签: c++ stl function-pointers


    【解决方案1】:

    正确的语法是这样的:

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

    太丑了。所以让我们试试这个:

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

    选择让你开心的。

    【讨论】:

    • 我试图理解语法,但我不明白为什么我不能只写 (*(result->second))();你能给我一个答案吗?谢谢
    • @Mike:要调用成员函数,您需要一个对象。那么为什么(*(result-&gt;second))(); 会起作用呢?调用成员的对象在哪里?
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多