zoukankan      html  css  js  c++  java
  • 实参时丢弃了类型 discards qualifiers discards qualifiers问题

    百思不得其解,于是百度,google吧。。

    发现Stackoverflow上也有人有相同的问题

    下面是他的问题:

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

    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() looks like this:

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

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

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

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

    Why am I getting this error?

    正确答案是

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

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

    意思是说  在一个加了const限定符的成员函数中,不能够调用 非const成员函数。

    因为如果调用了非const成员函数,就违反了const成员函数不改变对象的规定。

    而error:...discards qualifiers 的意思就是缺少限定符

    因此,他的解决办法很简单了 ,只要将checkElements()函数申明改为  checkElements()const就行了

  • 相关阅读:
    【转载】狐狸的故事
    【android】 资源路径
    【随笔】居然又玩了两天
    【android】 新浪oauth,进度条,AnimationDrawable,Toast,android预定义style
    【随笔】写下现在所想的,开始写博客
    【转】让我们如此享受的慢性毒药
    如何生成SPFILE文件
    如何区别存储过程中的EXIT与RUTURN
    如何设置虚拟机网络
    如何写SQLPLUS例子
  • 原文地址:https://www.cnblogs.com/senior-engineer/p/6196660.html
Copyright © 2011-2022 走看看