C++ 成员函数指针调用问题

查看:328
本文介绍了C++ 成员函数指针调用问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

大家好:

此段代码中当callFunc找到结果的时候,我该如何调用存在在map中的 指向对象成员的函数指针 ?

class A{
public:
    typedef void (A::*pf)(int);
    typedef map<string, pf> script_map;

    A() = default;
    script_map m1;

    void func1(int a){
        cout << a << endl;
    }

    int callFunc(const string& key){
        script_map::const_iterator iter = m1.find(key);
        if(iter != m1.end()){
            //ok
            (iter.*second)(1); // error: 'second' was not declared in this scope
        }else{
            //error
        }
    }
};

int main(int argc, char **argv){
    A obj;
    obj.m1.insert(make_pair("key1", &A::func1));
    obj.callFunc("key1");
}

以上,请各位指教

解决方案

(iter.*second)(1); // error: 'second' was not declared in this scope

应该改成

(this->*(iter->second))(1);

这篇关于C++ 成员函数指针调用问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆