【问题标题】:priority queue not compiling优先级队列未编译
【发布时间】:2020-03-31 22:59:56
【问题描述】:

我正在创建一个我创建的名为 Chore 的类的优先级队列。该类仅包含给定杂项的名称和该杂项的优先级,其中数字越大表示优先级越高。我用一个正常的队列测试了这个类,一切正常,所以我猜问题出在我的运算符过载上。 main函数创建5个Chore对象,将它们压入队列,然后依次输出队列。

家务课:

#include <string>
#include <iostream>
class Chore{
    public:
        Chore(std::string s = "N/A", int i = 0){chore = s; pnumber = i;}
        friend bool operator <(Chore c1, Chore c2){
            return c1.pnumber < c2.pnumber;
        }
        void input(){
            std::cout << "Enter type of chore: ";
            std::cin >> chore;
            std::cout << "Enter priority level: ";
            std::cin >> pnumber;
        }
        void output(){
            std::cout << "Chore: " << chore << std::endl << "Priority level: " << pnumber << std::endl;
        }
    private:
        std::string chore;
        int pnumber;
};

主要功能:

#include <queue>
#include "chore.h"
using namespace std;

int main(){
    priority_queue<Chore> q;
    Chore temp;
    for(int i = 0; i < 5; i++){
        temp.input();
        q.push(temp);
    }
    cout << endl;
    for(int i = 0; i < 5; i++){
        q.top().output();
        q.pop();
    }
}

我在编译时遇到的错误是:

error: passing 'const Chore' as 'this' argument discards qualifiers [-fpermissive]
         q.top().output();

问题是我的重载运算符吗?我该如何解决这个问题?

【问题讨论】:

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


    【解决方案1】:

    你的 output 函数需要是 const

     void output() const {
                std::cout << "Chore: " << chore << std::endl << "Priority level: " << pnumber << std::endl;
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-20
      • 2011-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      相关资源
      最近更新 更多