繁体   English   中英

用成员函数重载布尔运算符

[英]Overloading a bool operator with a member function

我有这样的课:

    class AI
    {
    private:
        struct Comparator
        {
            bool operator()(const Town* lfs, const Town* rhs)
            {
                return GetHeuristicCost(lfs) > GetHeuristicCost(rhs);
            }
        };
int GetHeuristicCost(const Town* town);
    // constructor and variables
    };

GetHeuristicCost返回从Town参数到路径exit的启发式方法。

我想做的是将布尔运算符重载到优先级队列,但这给了我错误

a nonstatic member reference must be relative to a specific object

我知道为什么会给我这个错误,但是我不知道如何在Comparator结构中使用非静态函数。

  1. GetHeuristicCost必须GetHeuristicCost静态
  2. 我试图将GetHeuristicCost Town类中无济于事
  3. 我需要用一个结构重载运算符,因为我需要在()上使用两个不同的布尔重载,用于两种不同的情况,但参数相同(两个镇)。 换句话说,我需要该结构,所以我不能这样做:

    bool operator()(const Town * lfs,const Town * rhs){返回GetHeuristicCost(lfs)> GetHeuristicCost(rhs ;; }

基本上我打算有两个这样的结构:

struct Comparator1
{
    bool operator()(const Town* lfs, const Town* rhs)
    {
        return GetHeuristicCost(lfs) > GetHeuristicCost(rhs);
    }
};

struct Comparator2
{
    bool operator()(const Town* lfs, const Town* rhs)
    {
        return GetHeuristicCost(lfs) + GetTotalCost (lfs, rhs) > GetHeuristicCost(rhs) + GetTotalCost (lfs, rhs);
    }
};

您需要使用指向其“外部”类实例的指针/引用来构造Comparator嵌套类的实例。

class AI
{
private:
    struct Comparator
    {
        const AI &outer;

        Comparator(const AI &o):outer(o){}

        bool operator()(const Town* lfs, const Town* rhs)const
        {
            return outer.GetHeuristicCost(lfs) > outer.GetHeuristicCost(rhs);
        }
    };

    int GetHeuristicCost(const Town* town)const;
};

// how to use in code:
AI::Comparator comp(*this);
priority_queue<Town*, vector<Town*>, AI::Comparator> priorityQueue(comp);

暂无
暂无

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

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