丢弃限定符错误

时间:2010-03-04 21:26:09

标签: c++

对于我的compsci类,我正在实现一个Stack模板类,但遇到了一个奇怪的错误:

  

Stack.h:在成员函数'const T Stack<T>::top() const [with T = int]':

     

Stack.cpp:10:错误:将“const Stack<int>”作为“this”参数传递给“void Stack<T>::checkElements() [使用T = int]”丢弃限定符

Stack<T>::top()看起来像这样:

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

Stack<T>::checkElements()看起来像这样:

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

堆栈使用链接节点进行存储,因此first_是指向第一个节点的指针。

为什么我收到此错误?

4 个答案:

答案 0 :(得分:21)

您的checkElements()功能未标记为const,因此您无法在const限定对象上调用它。

top(),但是const限定,因此在top()中,this是指向const Stack的指针(即使Stack实例上{ {1}}被称为非top()},因此您无法调用{em>总是需要非const实例的checkElements()。< / p>

答案 1 :(得分:13)

您不能从const方法调用非const方法。这将“丢弃” const 限定符。

基本上它意味着如果它允许你调用方法,那么它可以改变对象,这将破坏不修改方法签名末尾的const提供的对象的承诺。

答案 2 :(得分:4)

您正在从const方法调用非const方法。

答案 3 :(得分:2)

因为checkElements()未声明为const。

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

如果没有该声明,则无法在const对象上调用checkElements。