2015-11-05 37 views
-2

我想通过使用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

什么是编译器错误? – user463035818

+0

我对你的代码有点困惑。不应该是'void Chore :: output()const {...'? – user463035818

回答

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 {...} 
+1

立即编译。非常感谢你!你介意解释为什么我的代码是错误的,以及我的代码在被编译器解释时实际执行了什么? – user2905256

+2

在函数名称前具有const会影响返回类型。如果编译器不是一个指针或引用(实际上返回const bool相当于返回bool),它实际上会忽略一个const返回类型。我本来期望它会抱怨返回const void,但这是没有意义的。 – Kevin

+0

再次,谢谢。 – user2905256