在下面显示的简单代码中,有一个函数 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 method1
到 run7
而不改变 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/