【问题标题】:Why does this method for operator overloading not work here?为什么这种运算符重载方法在这里不起作用?
【发布时间】:2022-01-21 06:38:58
【问题描述】:
// program in c++ to use priority_queue with class
#include <iostream>
#include <queue>
using namespace std;

#define ROW 5
#define COL 2

class Person {

public:
    int age;

    float height;

    // this is used to initialize the variables of the class
    Person(int age, float height)
        : age(age), height(height)
    {
    }

    bool operator < (const Person& p1) {
        return (this->height > p1.height);
    }
};


// bool operator<(const Person& p1, const Person& p2)
// {
//  return p1.height > p2.height;
// }

// struct myCmp
// {
//     bool operator() (const Person& p1, const Person& p2) {
//         return p1.height > p2.height;
//     }
// };


int main()
{

    priority_queue<Person> Q;

    float arr[ROW][COL] = { { 30, 5.5 }, { 25, 5 },
            { 20, 6 }, { 33, 6.1 }, { 23, 5.6 } };

    for (int i = 0; i < ROW; ++i) {

        Q.push(Person(arr[i][0], arr[i][1]));

        // insert an object in priority_queue by using
        // the Person class constructor
    }

    while (!Q.empty()) {

        Person p = Q.top();

        Q.pop();

        cout << p.age << " " << p.height << "\n";
    }
    return 0;
}

注意! 代码中的其他注释方法似乎有效,除了这给了我一个错误。

上面的代码是为了让身高较低的人排在最前面而创建一个优先队列。我尝试使用 struct 方法来定义似乎工作正常的自定义比较函数。上述 cmets 中的显式运算符重载也有效。

预期输出:

25 5

30 5.5

23 5.6

20 6

33 6.1

错误:

'operator

【问题讨论】:

  • 该错误表明operator&lt; 正在应用到 const Person。您的运算符只有右手值作为 const。将您的 operator&lt; 声明为 const。

标签: c++ operator-overloading priority-queue


【解决方案1】:

错误信息:

'operator

这告诉你 operator 的 lhs 和 rhs 对象是 const 对象。并且编译器找不到可以处理两个 const Person 对象的运算符。

如果我看看你的实现:

bool operator < (const Person& p1) {
    return (this->height > p1.height);
}

我看到右边的值p1 可以是一个常量引用。但是左侧值(方法的所有者)被视为非成本。所以这个实现不符合所需的要求。

但是我们知道这个操作符并没有改变对象的状态,所以我们可以简单地将它标记为一个 const 成员函数。

bool operator < (const Person& p1) const {
                             //    ^^^^^    Add the const here.
    return (this->height > p1.height);
}

【讨论】:

    猜你喜欢
    • 2013-05-28
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    相关资源
    最近更新 更多