通过参数接收到的对象的功能指针

Function pointer on object received by parameter

本文关键字:对象 功能 指针 参数      更新时间:2023-10-16

i具有接收对象实例和功能指针的函数。如何在对象实例上执行我的功能指针?

我尝试过:

void    Myclass::my_fn(Object obj, bool (*fn)(std::string str))
{
   obj.fn("test"); // and (obj.fn("test"))
}

,但没有任何作用。它告诉我"未使用的参数my_fn和fn"

这是因为 fn不是 Object成员函数指针。为此,您必须做例如。

bool (Object::*fn)(std::string)

然后称呼它必须做

(obj.*fn)(...);

但是,如果您的编译器和库可以支持C 11,我建议您使用std::functionstd::bind

void MyclasS::my_fn(std::function<bool(std::string)> fn)
{
    fn("string");
}

然后将my_fn函数称为

using namespace std::placeholders;  // For `_1` below
Object obj;
myclassobject.my_fn(std::bind(&Object::aFunction, &obj, _1));

使用std::function,您还可以使用其他功能指针或lambdas:

myclassobject.my_fn([](std::string s){ std::cout << s << 'n'; return true; });

函数指针是完全不同的形式成员函数指针(用于方法的指针)。

在功能指针的情况下,您不需要任何对象来调用它们:

void    Myclass::my_fn(bool (*fn)(std::string str))
{
   fn("test");
}

如果成员函数指针正确的语法为:

void    Myclass::my_fn(Object obj, bool (Object::*fn)(std::string str))
{
   obj.*fn("test");
}