c++ - 如何用成员函数初始化一个成员函数指针

标签 c++

我想为我的类(class)创建一个比较函数 (cmp)。如果构造函数有一个函数参数就好了。如果不是,我想为它设置一个默认值,有什么想法吗?

下面是我的代码,

template<class T>
class BinaryHeap{
public:
    BinaryHeap();
    explicit BinaryHeap(bool (*cmp)(T, T));
private:
    bool (*cmp)(T ele_a, T ele_b); // function pointer
    bool default_cmp(T ele_a, T ele_b);
};
template<class T>
BinaryHeap<T>::BinaryHeap() {
    //the code bellow is not work;
    this->cmp = default_cmp; // there is problem
}
template<class T>
BinaryHeap<T>::BinaryHeap(bool (*cmp)(T, T)) {
    heap_size = 0;
    this->cmp = cmp; // this is ok for the compiler
}

最佳答案

只要改变这个

bool default_cmp(T ele_a, T ele_b);

对此

static bool default_cmp(T ele_a, T ele_b);

常规成员函数与函数指针不兼容,但静态成员函数是。

关于c++ - 如何用成员函数初始化一个成员函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55217488/

相关文章:

C++ 无法循环指向 vector 的 vector 的指针

c++ - 使用工厂填充元组并避免复制

c++ - 如何通过平移、旋转和缩放反转仿射变换?

c++ - "if constexpr()"与 "if()"之间的区别

c++ - 我可以将反向迭代器转换为正向迭代器吗?

c++ - SDL 不加载/显示正确的图像

c++ - 调用 const 函数而不是其非 const 版本

c++ - 如何将有界重复匹配为仅 n 和 m 次

c++ - 如何使用虚表正确调用成员方法?

c++ - 如何在不使用 makefile 的情况下链接目标文件和库