当我将方法名称传递给其他类方法时,它显示此错误:
$ g++ test.cpp -std=c++17
test.cpp: In member function ‘void Test::finish()’:
test.cpp:18:38: error: invalid use of non-static member function ‘bool
Test::local_method(std::__cxx11::string)’
t.add_method(local_method);
^
test.cpp:16:14: note: declared here
bool local_method(string msg) {}
test.cpp
:
#include <functional>
#include <string>
using namespace std;
class Main {
public:
void add_method(function<bool(string)> fn) {
// ...
}
};
Main t;
class Test {
public:
bool local_method(string msg) {}
void finish() {
t.add_method(local_method);
}
};
int min() {
Test a;
a.finish();
}
当我不使用类时,它可以在其他代码中工作:
void call(int a, function<int(int)> x) {
cout << "--->>>" << x(a) << endl;
}
int give_an_int(int a) {
return a * 123;
}
call(11, give_an_int);