c++ - 如何将另一个类的函数作为参数传递?

标签 c++

我想将另一个类的函数作为参数传递到我当前的类中。我正在尝试做这样的事情(我简化了代码,所以你仍然可以理解这个想法):

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.myCmpFunctB::myCmpFunc&B::myCmpFunc 传递,但是我仍然有错误。

最佳答案

当你有一个class函数(类中的非静态函数)时,你需要传递this/类的实例,这样编译器就可以通过this/调用函数时对象的实例。

您可以:

  1. 使您的函数静态。类中的 static 函数不使用 this/对象实例,因此它们的指针是正常的。

static bool B::myCmpFunc(int a, int b) {}
b.sort(&b.myCmpFunc);
// or
b.sort(&B::myCmpFunc);
  1. 您可以重构您的函数以使用 std::function 并使用 std::bindthis 与对象指针绑定(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));
  1. 重构您的函数以仅采用 B 类函数。

vector<int> B::sort(bool (B::*cmp)(int a, int b)) {
       ...
       (this->*cmp)(...);
       ...
}
b.sort(&B::myCmpFunc);
  1. 使用 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); });
  1. 还有更多(例如模板)。

由于成员函数 B::myCmpFunc 似乎没有使用 this 指针或对象成员,所以我将声明它为 static.

关于c++ - 如何将另一个类的函数作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55412920/

相关文章:

c++ - 双继承类型推导

c++ - 从 C++ 文件中读取行的首选模式是什么?

c++ - 在 C++ 中逐行读取文件(每行有一个字符串和几个 int 值)?

c++ - 套接字的异常服务器行为

c++ - 删除谁的责任

c++ - OpenCV - 在同一个程序中收集 featureDetectors 和 descriptorDetector

c++ - 接口(interface)(抽象类)与其他虚拟更改的 ABI 兼容性

c++ - 使用 NULL 类指针,可以调用类成员函数。这怎么可能?

c++ - 无法理解模板类中的友元函数

c++ - 从 std::vector 创建点云