丢弃限定符错误

2023-12-08

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

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

Stack.cpp:10:错误:传递‘const Stack<int>’ as ‘this' 的论证void Stack<T>::checkElements()[with 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_是指向第一个节点的指针。

为什么我会收到此错误?


Your checkElements()函数未标记为const所以你不能调用它const合格的对象。

top(),但是 const 限定所以在top(), this是一个指向 const 的指针Stack(即使Stack其上的实例top()被称为恰好是非const),所以你不能打电话checkElements() which always需要一个非const实例。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

丢弃限定符错误 的相关文章

随机推荐