如何修复此丢弃限定符错误?

时间:2015-11-05 22:21:01

标签: c++

我正在尝试通过使用STL优先级队列来实现基于其优先级的杂项列表。当我尝试编译时,我收到了关于输出函数和重载<的错误。运营商。香港专业教育学院尝试使用const函数,但这并没有解决问题。我该如何解决这个问题?

main.cc

priority_queue<Chore> chores;
Chore tmp;

for(int  i = 5; i >0; i--) {
  tmp.input(cin);
  chores.push(tmp);
}

while(!chores.empty()) {
  chores.top().output();
  chores.pop();
}

return 0;

};

chore.h

class Chore {
  public:
    Chore();
    void input(istream& ins);
    void const output();
    bool const operator <(const Chore c1);

  private:
    string chore_name;
    int priority;
};

chore.cc

Chore:: Chore() {
  chore_name = "";
  priority = 0;
};

void Chore:: input(istream& ins) {
  cout << "Please Enter the name of the chore: ";
  cin >> chore_name;
  cout << endl << "Please Enter The Priority Level: ";
  cin >> priority;
  cout << endl;
};

void const Chore:: output() {
  cout << "Chore: " <<  chore_name << endl;
  cout << "Priority: " << priority << endl << endl;
};

bool const Chore:: operator <(const Chore c1) {
   return (priority < c1.priority);
};

1 个答案:

答案 0 :(得分:3)

你不能使成员函数成为常量。这样做:

class Chore {
    ...
    void output() const;
    bool operator<(const Chore& c1) const; //Also added pass by reference here
};
void Chore::output() const {...}
bool Chore::operator<(const Chore& c1) const {...}