c++ - 如何用成员函数初始化成员函数指针
问题描述
我想为我的班级创建一个比较函数 (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);
常规成员函数与函数指针不兼容,但静态成员函数兼容。
推荐阅读
- javascript - iframe body 上的 ResizeObserver 在 Chrome 和 Firefox 上的行为不同
- angular - 尝试从.net核心WebApi并行执行多个调用中的多个存储过程
- python - 如何在 PySimpleGUI 上获得 pandastable?
- python - Python joblib Parallel n_jobs=1 正在工作。n_jobs=2 不工作。没有错误。空输出。nmslib 模型管道
- excel - 当我在工作簿中添加此代码时收到错误
- java - 我如何告诉 maven 我希望编译后的代码去哪里?
- python - 如何在不使用 reverse() 且不使用 return 的情况下反转列表
- php - 我想将过滤后的数据从数据库发送到我的邮件
- azure-devops - 如何使用 powershell 命令创建名称和机密作为输入参数的 Azure AD B2C 身份体验框架策略密钥
- flutter - 如何使用 Flutter 向 googleSignIn 添加范围