加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 放弃限定符错误

发布时间:2020-12-16 02:59:08 所属栏目:百科 来源:网络整理
导读:对于我的compsci类,我正在实现一个Stack模板类,但遇到一个奇怪的错误: Stack.h: In member function ‘ const T StackT::top() const [with T = int]’: Stack.cpp:10: error: passing ‘ const Stackint ’ as ‘ this ’ argument of ‘ void StackT::che
对于我的compsci类,我正在实现一个Stack模板类,但遇到一个奇怪的错误:

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()看起来像这样:

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

堆栈< T> :: checkElements()如下所示:

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

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

为什么我得到这个错误?

解决方法

你的checkElements()函数没有被标记为const,所以你不能在const限定对象上调用它.

top(),但是在top()中是const限定的,这是一个指向const Stack的指针(即使调用了top()的Stack实例也是非const),所以你不能调用checkElements (),它总是需要一个非常量的实例.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读