C++ 如何通过迭代器通过指针调用函数?

C++ 如何通过迭代器通过指针调用函数?,c++,pointers,C++,Pointers,我声明了一个全局类型: typedef void ( MyClass::*FunctionPtr ) ( std::string ); 然后我需要在我的函数中使用它: void MyClass::testFunc() { } void MyClass::myFunction() { std::map < std::string, FunctionPtr > ptrsMap; ptrsMap[ "first" ] = &MyClass::testFunc;

我声明了一个全局类型:

typedef void ( MyClass::*FunctionPtr ) ( std::string );
然后我需要在我的函数中使用它:

void MyClass::testFunc() {
}
void MyClass::myFunction() {

    std::map < std::string, FunctionPtr > ptrsMap;
    ptrsMap[ "first" ] = &MyClass::testFunc;

    std::map < std::string, FunctionPtr >::iterator it;
    it = ptrsMap.begin();

    ( *it->second ) ( "param" );    // How to call this function?

}

但我需要使用局部变量调用该函数。

FunctionPtr
是成员函数指针,因此需要对对象调用它。 使用指向成员绑定运算符的指针
*

MyClass object;
...
(object.*it->second)("param")

FunctionPtr
是成员函数指针,因此需要对对象调用它。 使用指向成员绑定运算符的指针
*

MyClass object;
...
(object.*it->second)("param")

成员函数需要与实例关联

    MyClass k;
    (k.*it->second)("param");
也可以使用当前对象

(*this.*it->second)("param");

您的
testFunc
还需要获取字符串参数。

成员函数需要与实例关联

    MyClass k;
    (k.*it->second)("param");
也可以使用当前对象

(*this.*it->second)("param");

另外,您的
testFunc
需要获取一个字符串参数。

问题在于成员函数需要应用一个对象

一种方法是使用函数对象:

auto f = std::bind(it->second, this, std::placeholders::_1);  // first bind is for object
f (std::string("param"));    // How to call this function?
顺便说一下,在代码示例中,您应该将测试函数的签名更正为:

void MyClass::testFunc(std::string)  //  FunctionPtr requires a string argument 

问题是成员函数需要应用一个对象

一种方法是使用函数对象:

auto f = std::bind(it->second, this, std::placeholders::_1);  // first bind is for object
f (std::string("param"));    // How to call this function?
顺便说一下,在代码示例中,您应该将测试函数的签名更正为:

void MyClass::testFunc(std::string)  //  FunctionPtr requires a string argument 

成员函数指针是重要的thing@LightnessRacesinOrbit但我怎么称呼它呢?:)
it
不需要是全局变量,因为成员函数指针是重要的thing@LightnessRacesinOrbit但我怎么称呼它呢?:)
it
不需要是一个全局变量,但是我不能创建一个对象,因为我已经停留在itOr中调用对象本身:
(this->*it->second)(“param”)
等等,但是我不能创建一个对象,因为我已经停留在itOr中调用对象本身:
(this->*it->second)(“param”)
但如果需要在对象内部调用该函数,如何创建该对象?:)但是,如果需要在对象内部调用该函数,如何创建该对象呢?:)