discard qualifiers的錯誤

寫代碼時,沒有注意到或者說不清楚的問題,discard qualifiers的問題,網上有人碰到此類問題並附介紹:

For my compsci class, I am implementing a Stack template class, but have run into an odd error:

Stack.h: In member function ‘const T Stack<T>::top() const [with T = int]’:

Stack.cpp:10: error: passing ‘const Stack<int>’ as ‘this’ argument of ‘void Stack<T>::checkElements() [with T = int]’ discards qualifiers

Stack<T>::top() looks like this:

const T top() const {
    checkElements();
    return (const T)(first_->data);
}

Stack<T>::checkElements() looks like this:

void checkElements() {
    if (first_==NULL || size_==0)
        throw range_error("There are no elements in the stack.");
}

The stack uses linked nodes for storage, so first_ is a pointer to the first node.

Why am I getting this error?


正確答案是

Your checkElements() function is not marked as const so you can't call it on const qualified objects.

top(), however is const qualified so in top()this is a pointer to a const Stack (even if theStack instance on which top() was called happens to be non-const), so you can't callcheckElements() which always requires a non-const instance.

意思是說  在一個加了const限定符的成員函數中,不能夠調用 非const成員函數。

因爲如果調用了非const成員函數,就違反了const成員函數不改變對象的規定。

而error:...discards qualifiers 的意思就是缺少限定符

因此,他的解決辦法很簡單了 ,只要將checkElements()函數申明改爲  checkElements()const就行了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章