【发布时间】:2019-06-22 02:31:02
【问题描述】:
我是 lambdas 新手,我用自定义比较器函数创建了自己的二进制堆类。 一切顺利,直到我遇到编译错误并且我不知道如何修复。
我试图改变我的代码行,而不是
this(capacity, [](int a, int b){return a - b;});
我改成这样了:
function<int(int, int)> cmp = [](int a, int b){return a - b;};
this(capacity, cmp);
我得到了同样的结果。如何处理这个错误?
二进制堆类:
class binaryheap
{
private:
int *heap;
int size;
int capacity;
function<int(int, int)> cmp;
int parent(int i);
int left_child(int i);
int right_child(int i);
void swap(int *a, int *b);
void heapify(int i);
public:
binaryheap(int capacity);
binaryheap(int capacity, const function<int(int, int)>& cmp);
~binaryheap();
bool empty();
int heap_size() const;
int get_root() const;
int extract_root();
void decrease_key(int i, int value);
void insert_key(int key);
void delete_key(int i);
};
我的代码有编译错误的部分
binaryheap::binaryheap(int capacity)
{
this(capacity, [](int a, int b){return a - b;});//binaryheap.cpp:51:58: error: expression cannot be used as a function
}
binaryheap::binaryheap(int capacity, const function<int(int, int)>& cmp)
{
this->capacity = capacity;
this->heap = new int[capacity + 1];
this->size = 0;
this->cmp = cmp;
}
【问题讨论】:
-
嗯,是的。
this是指向您的对象的指针;这不是一个功能。你想用this( ... )做什么? -
我从 Java 中了解到 this(...) 会调用对象的构造函数。
-
C++ 不是 Java。
-
您的大部分代码都是不必要的。你的错误可以减少到
struct foo { void bar() { this(); } };。
标签: c++ c++11 lambda std-function delegating-constructor