Discards qualifiers error

前端 未结 4 624
臣服心动
臣服心动 2020-11-29 11:09

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

相关标签:
4条回答
  • Because checkElements() isn't declared const.

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

    Without that declaration, checkElements cannot be called on a const object.

    0 讨论(0)
  • 2020-11-29 11:55

    You cannot call a non-const method from a const method. That would 'discard' the const qualifier.

    Basically it means that if it allowed you to call the method, then it could change the object, and that would break the promise of not modifying the object that the const at the end of the method signature offers.

    0 讨论(0)
  • 2020-11-29 11:56

    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 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.

    0 讨论(0)
  • 2020-11-29 12:04

    You're calling a non-const method from a const method.

    0 讨论(0)
提交回复
热议问题