C++ 丢弃限定符错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2382834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Discards qualifiers error
提问by Austin Hyde
For my compsci class, I am implementing a Stack template class, but have run into an odd error:
对于我的 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.h:在成员函数“
const T Stack<T>::top() const
[with T = int]”中:Stack.cpp:10: 错误:将 '
const Stack<int>
' 作为this
'void Stack<T>::checkElements()
[with T = int]'的参数传递会丢弃限定符
Stack<T>::top()
looks like this:
Stack<T>::top()
看起来像这样:
const T top() const {
checkElements();
return (const T)(first_->data);
}
Stack<T>::checkElements()
looks like this:
Stack<T>::checkElements()
看起来像这样:
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.
堆栈使用链接节点进行存储,因此first_
是指向第一个节点的指针。
Why am I getting this error?
为什么我收到这个错误?
回答by CB Bailey
Your checkElements()
function is not marked as const
so you can't call it on const
qualified objects.
你的checkElements()
函数没有被标记为const
所以你不能在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 alwaysrequires a non-const
instance.
top()
不过是const修饰所以top()
,this
是一个指向一个常量Stack
(即使Stack
在其实例top()
被称为恰好是非const
),所以你不能把checkElements()
它总是需要一个非const
实例。
回答by David Rodríguez - dribeas
You cannot call a non-const method from a const method. That would 'discard' the constqualifier.
不能从 const 方法调用非常量方法。这将“丢弃” const限定符。
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.
基本上这意味着如果它允许您调用该方法,那么它可以更改对象,这将破坏不修改const
方法签名末尾提供的对象的承诺。
回答by Dave Bacher
You're calling a non-const method from a const method.
您正在从 const 方法调用非常量方法。
回答by Dave Bacher
Because checkElements() isn't declared const.
因为 checkElements() 没有被声明为 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.
如果没有该声明,则无法在 const 对象上调用 checkElements。