【问题标题】:Overloading a bool operator with a member function使用成员函数重载布尔运算符
【发布时间】:2014-01-02 21:21:49
【问题描述】:

我有这样的课:

    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 将城镇参数的启发式返回到路径的exit

我想要做的是为优先级队列重载 bool 运算符,但它给了我错误

a nonstatic member reference must be relative to a specific object

我知道为什么会出现此错误,但我不知道如何在 Comparator 结构中使用非静态函数。

  1. GetHeuristicCost 必须是非静态的
  2. 我尝试在 Town 类中移动 GetHeuristicCost 无济于事
  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);
    }
};

【问题讨论】:

    标签: c++ function struct operator-overloading non-static


    【解决方案1】:

    您需要使用指向其“外部”类实例的指针/引用来构造 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);
    

    【讨论】:

    • 我尝试在我的一个函数中使用它,例如 Comparator comp(*this); priority_queue&lt;Town*, vector&lt;Town*&gt;, comp&gt;priorityQueue; 但它给我的错误是 comp 不是类型名称
    • priority_queue, AI::Comparator>priorityQueue
    • 我试过了,但它不喜欢我没有创建比较器实例的事实。它给了我不存在默认构造函数的错误。我也不知道这是否重要,但我从AI &amp;outerAI &amp;o 中删除了const,因为我的AI 对象不断变化。
    • 查看我的编辑。还要确保你的 AI 不断变化,但 GetHueristicCost 真的会修改它吗?如果您正在执行 A* 之类的操作,则可能是只读操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多