【问题标题】:Error: expression cannot be used as an function错误:表达式不能用作函数
【发布时间】: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;
}

【问题讨论】:

标签: c++ c++11 lambda std-function delegating-constructor


【解决方案1】:

我想你想使用委托构造函数;所以

 binaryheap::binaryheap (int capacity)
     : binaryheap{capacity, [](int a, int b){return a - b;}}
  { }

或者,按照 melpomene 的建议(谢谢),您可以删除此构造函数并为另一个构造函数中的第二个参数添加默认值 ([](int a, int b){return a - b;})。

【讨论】:

  • 但请确保您使用的是 c++11 或更高版本
  • 或者只使用一个带有默认参数的构造函数。
  • @SaraTarek - OP 使用 lambda 函数和 std::function,因此使用 C++11 或更高版本。
  • @melpomene - 你是对的;应该是显而易见的,但最好是明确的。谢谢。
猜你喜欢
  • 2022-11-12
  • 2022-01-10
  • 2015-03-06
  • 2022-01-06
  • 2019-02-13
  • 1970-01-01
  • 2023-03-21
  • 2020-06-30
  • 1970-01-01
相关资源
最近更新 更多