C++ 将另一个方法作为参数传递

标签 c++ function c++11 function-pointers

在下面显示的简单代码中,有一个函数 run7,它接收一个函数作为参数。在 main 函数中,一个函数 test 被传递给它并且它工作正常。但是,我的 method2 无法将 method1 传递给此函数。它导致错误:

main.cpp:24:15: error: cannot convert ‘A::method1’ from type ‘void (A::)(int)’ to type ‘void (*)(int)’
   run7(method1);
               ^

我想调用 pass method1run7 而不改变 run7 的结构。如何修复 method2

#include <iostream>

using namespace std;

void run7 ( void (*f)(int) )
{
    f(7);
}

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

class A
{
public:

    int m=4;

    void method1(int a)
    {
        cout<< a*m <<endl;
    }

    void method2()
    {
        run7(method1);
    }
};

int main()
{
    run7(test);
    return 0;
}

最佳答案

如果您仔细查看错误:

error: cannot convert ‘A::method1’ from type ‘void (A::)(int)’ to type ‘void (*)(int)’

您会看到类型不同。那是因为类方法与原始函数的类型不同——它们需要额外的对象才能被调用。无法编译该代码,因为调用 method1 需要一个 A,它需要无法作为原始函数指针传入的存储。

您可以做的是更改 run 以采用类型删除的仿函数:

void run7 ( std::function<void(int)> f ) {
    f(7);
}

然后传入一个仿函数,它也传入 this:

void method2()
{
    run7(std::bind(&A::method1, this,           // option 1
                   std::placeholders::_1)); 
    run7([this](int x){ this->method1(x); });   // option 2
}

关于C++ 将另一个方法作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27974628/

相关文章:

c++ - 在基于 for 循环的范围内复制省略

c++ - 没有dup的execl管道

c - 使用递归反转c中的字符串

c++ - 当我希望线程终止时,删除包含正在运行的线程的类是否可以/安全?

c++ - 如何将 unique_ptr 捕获到 lambda 表达式中?

循环内的 JavaScript 函数

c++ - 在 64 位中进行组合乘除运算的最准确方法是什么?

c++ - 汇编代码中的静态值

c++ - 从指针 vector 中安全删除

统计一个C函数执行了多少次