丢弃限定符错误 [英] Discards qualifiers error

查看:125
本文介绍了丢弃限定符错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


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

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

Stack.cpp:10:错误:传递 const Stack 'as' this ' ' void Stack< T> :: checkElements() [with T = int]'丢弃限定符

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


b $ b

Stack< T> :: top()如下所示:

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

Stack< T> :: checkElements / code>看起来像这样:

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

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

堆栈使用链接节点进行存储,因此 first_

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

为什么会收到此错误?

推荐答案

您的 checkElements()函数未标记为 const 不能在 const 限定对象上调用。

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

c $ c>,但是const限定,因此在 top()是指向一个const < c $ c> Stack (即使在 top() Stack 所以你不能调用 checkElements()其中总是 / em>需要一个非 - const 实例。

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

这篇关于丢弃限定符错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆