我想将另一个类的函数作为参数传递给当前类。我正在尝试做这样的事情(我简化了代码,因此您仍然可以理解):
B class:
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 class
:
B b;
auto sortedElems = b.sort(&b.myCmpFunc);
问题是,当我尝试将&b.myCmpFunc作为参数传递给时,出现此错误A class
:
错误C2276'&':对绑定成员函数表达式的非法操作
我也尝试过其他的东西,比如传递函数为b.myCmpFunct
,B::myCmpFunc
,&B::myCmpFunc
,但我仍然有错误。
当您有一个class
函数(类中的非静态函数)时,您需要传递this
该类的实例,以便编译器可以this
在调用该函数时将对象的实例传递给该函数。
您可以:
static
。static
类中的函数不使用this
/对象实例,因此它们的指针是正常的。static bool B::myCmpFunc(int a, int b) {}
b.sort(&b.myCmpFunc);
// or
b.sort(&B::myCmpFunc);
std::function
并this
与对象指针绑定std::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);
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
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句