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

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);
【热门文章】
【热门文章】