我想将另一个类的函数作为参数传递到我当前的类中。我正在尝试做这样的事情(我简化了代码,所以你仍然可以理解这个想法):
B类:
bool B::myCmpFunc(int a, int b) {
return a > b;
}
vector<int> B::sort(bool (*cmp)(int a, int b)) {
vector<int> elems = getElems();
for (int i = 0; i < elems.size() - 1; i++) {
for (int j = i + 1; j < elems.size(); j++) {
if ((*cmp)(elems[i], elems[j])) {
int aux = elems[i];
elems[i] = elems[j];
elems[j] = aux;
}
}
}
return elems;
}
然后我尝试从 A 类
调用这个排序函数:
B b;
auto sortedElems = b.sort(&b.myCmpFunc);
问题是当我尝试将 &b.myCmpFunc 作为 A 类
中的参数传递时出现此错误:
Error C2276 '&': illegal operation on bound member function expression
我还尝试了其他方法,比如将函数作为 b.myCmpFunct
、B::myCmpFunc
、&B::myCmpFunc
传递,但是我仍然有错误。
最佳答案
当你有一个class
函数(类中的非静态函数)时,你需要传递this
/类的实例,这样编译器就可以通过this
/调用函数时对象的实例。
您可以:
- 使您的函数
静态
。类中的static
函数不使用this
/对象实例,因此它们的指针是正常的。
static bool B::myCmpFunc(int a, int b) {}
b.sort(&b.myCmpFunc);
// or
b.sort(&B::myCmpFunc);
- 您可以重构您的函数以使用
std::function
并使用std::bind
将this
与对象指针绑定(bind)。
vector<int> B::sort(std::function<bool(int a, int b)> cmp) {
... no changes ...
}
b.sort(std::bind(&B::myCmpFunc, &b, std::placeholders::_1, std::placeholders::_2));
- 重构您的函数以仅采用
B
类函数。
vector<int> B::sort(bool (B::*cmp)(int a, int b)) {
...
(this->*cmp)(...);
...
}
b.sort(&B::myCmpFunc);
- 使用 lambda。
b.sort([](int a, int b) -> bool { return a < b; });
// really or
b.sort([&b](int a, int b) -> bool { return b.myCmpFunc(a, b); });
- 还有更多(例如模板)。
由于成员函数 B::myCmpFunc
似乎没有使用 this
指针或对象成员,所以我将声明它为 static
.
关于c++ - 如何将另一个类的函数作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55412920/