丢弃限定符错误 [英] Discards qualifiers error
问题描述
对我的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
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屋!