简体   繁体   English

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

[英]Overloading a bool operator with a member function

I have a class like this: 我有这样的课:

    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 returns the heuristic from the town parameter to the exit of the path. GetHeuristicCost返回从Town参数到路径exit的启发式方法。

What I am trying to do is overload the bool operator for a priority queue but it gives me the error 我想做的是将布尔运算符重载到优先级队列,但这给了我错误

a nonstatic member reference must be relative to a specific object

I know why it is giving me this error but what I don't know is how to use a nonstatic function inside the Comparator struct. 我知道为什么会给我这个错误,但是我不知道如何在Comparator结构中使用非静态函数。

  1. GetHeuristicCost must be nonstatic GetHeuristicCost必须GetHeuristicCost静态
  2. I tried moving GetHeuristicCost inside the Town class to no avail 我试图将GetHeuristicCost Town类中无济于事
  3. I need to overload the operator with a struct because I need to use two different bool overloadings on the () for two different circumstances but with the same parameters (two Towns). 我需要用一个结构重载运算符,因为我需要在()上使用两个不同的布尔重载,用于两种不同的情况,但参数相同(两个镇)。 In other words I need the struct so I can't do this: 换句话说,我需要该结构,所以我不能这样做:

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

Basically I plan on having two structs like this: 基本上我打算有两个这样的结构:

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);
    }
};

You need to construct instances of the Comparator nested class with a pointer/reference to their "outer" class instance. 您需要使用指向其“外部”类实例的指针/引用来构造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