繁体   English   中英

功能对象和功能指针之间的区别?

[英]the differences between function-object and function-pointer?

我定义了一个类,然后将指向Foo的指针保存在priority_queue中,并使用我定义的cmp函数。

但是,如果cmp-funtion调用了功能对象,则会发生错误:

class Foo
{
    friend bool cmp(Foo *, Foo *);
public:
    Foo() = default;
    Foo(int x):val(x) {}
private:
    int val;
};
bool cmp(Foo *a, Foo *b)
{
    return a->val < b->val;
}
int main()
{
    priority_queue<Foo*, vector<Foo*>, decltype(cmp)*> que;
    que.push(new Foo(5));
    que.push(new Foo(6));
    return 0;
}

功能对象正常运行。

class Foo
{
    friend struct cmp;
public:
    Foo() = default;
    Foo(int x):val(x) {}
private:
    int val;
};
struct cmp
{
    bool operator()(Foo *a, Foo *b)
    {
        return a->val < b->val;
    }
};
int main()
{
    priority_queue<Foo*, vector<Foo*>, cmp> que;
    que.push(new Foo(5));
    que.push(new Foo(6));
    return 0;
}

您需要使用希望用作比较的函数来构造que变量。

#include <vector>
#include <queue>

using namespace std;

class Foo
{
    friend bool cmp(Foo*, Foo*);
public:
    Foo() = default;
    Foo(int x):val(x) {}
private:
    int val;
};
bool cmp(Foo* a, Foo* b)
{
    return a->val < b->val;
}
int main()
{
    //                                                     vvv
    priority_queue<Foo*, vector<Foo*>, decltype(cmp)*> que(cmp);
    que.push(new Foo(5));
    que.push(new Foo(6));

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM