c++ - 使用成员函数重载 bool 运算符

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

我有这样一个类:

    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 返回从 t​​own 参数到路径的 exit 的启发式。

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

a nonstatic member reference must be relative to a specific object

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

  1. GetHeuristicCost 必须是非静态的
  2. 我尝试将 GetHeuristicCost 移动到 Town 类中,但没有成功
  3. 我需要使用结构重载运算符,因为我需要在 () 上使用两个不同的 bool 重载以用于两种不同的情况但具有相同的参数(两个城镇)。换句话说,我需要结构,所以我不能这样做:

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

关于c++ - 使用成员函数重载 bool 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20594765/

相关文章:

c++ - 使用 BCL 进行文件压缩

c++ - MatLab C++ 共享 Dll 库初始化崩溃

c++ - 使用模板的空对象或类/空类型

mysql - 我可以创建一个过程或函数来删除 mysql 中的参数表吗?

c++ - 计算给定 log(x) 和 log(y) 的 log(x - y),没有溢出?

javascript - 函数名是否充当变量?

javascript - 使用用户定义函数时 map 消失

pointers - 指向方法参数中接口(interface)的指针?

c++ - 为什么 64 位和 32 位系统中的 Struct 填充相同?

比较 2 个字符串,一个在结构中,另一个不是 C 编程