【问题标题】:Discards qualifiers error丢弃限定符错误
【发布时间】:2010-03-04 21:26:08
【问题描述】:

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

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

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

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_ 是指向第一个节点的指针。

为什么会出现这个错误?

【问题讨论】:

    标签: c++


    【解决方案1】:

    您的checkElements() 函数未标记为const,因此您不能在const 合格对象上调用它。

    top(),但是是 const 限定的,所以在 top() 中,this 是指向 const Stack 的指针(即使调用 top() 的 Stack 实例恰好是非@ 987654330@),因此您不能调用checkElements(),因为它总是需要非const 实例。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

          因为 checkElements() 没有声明为 const。

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2022-01-07
            • 2014-02-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-08-26
            相关资源
            最近更新 更多