g ++:const丢弃限定符 [英] g++: const discards qualifiers
问题描述
为什么我得到放弃限定符
错误:
why do I get a discard qualifiers
error:
customExc.cpp: In member function ‘virtual const char* CustomException::what() const’:
customExc.cpp: error: passing ‘const CustomException’ as ‘this’ argument of ‘char customException::code()’ discards qualifiers
关于以下代码示例
#include <iostream>
class CustomException: public std::exception {
public:
virtual const char* what() const throw() {
static std::string msg;
msg = "Error: ";
msg += code(); // <---------- this is the line with the compile error
return msg.c_str();
}
char code() { return 'F'; }
};
在讨论类似问题之前,我已经在SOF上搜索过。
I have searched around on SOF before regarding simular issues.
我已经在每一个可能的地方添加了一个 const
。
I have already added a const
on every possible place.
请赐教 - 我不要't明白了......
Please enlighten me - I don't get the point...
编辑:
这里是在Ubuntu-Carmic-32bit(g ++ v4.4.1)
EDIT: here are the steps to reproduce on Ubuntu-Carmic-32bit (g++ v4.4.1)
- 将示例另存为
customExc.cpp
- 输入
make customExc.o
- save example as
customExc.cpp
- type
make customExc.o
编辑:错误与 CustomException
有关。类 Foo
与它无关。所以我删除了它。
EDIT: The error is related to CustomException
. The class Foo
has nothing to do with it. So I have deleted it.
推荐答案
CustomException :: what
是一个const方法,由const 在后指明what()
。由于它是一个常量方法,它不能做任何可能会修改的东西。 CustomException :: code
不是一个const方法,这意味着它不承诺不修改自己。因此 CustomException :: what
无法调用 CustomException :: code
。
CustomException::what
calls CustomException::code
. CustomException::what
is a const method, as signified by the const after what()
. Since it is a const method, it cannot do anything that may modify itself. CustomException::code
is not a const method, which means that it does not promise to not modify itself. So CustomException::what
can't call CustomException::code
.
请注意,const方法不一定与const实例相关。 Foo :: bar
可以将 exc
变量声明为非const并调用const方法,如 CustomException ::什么
;这只是意味着 CustomException :: what
承诺不会修改 exc
,但其他代码可能会是。
Note that const methods are not necessarily related to const instances. Foo::bar
can declare its exc
variable as non-const and call const methods like CustomException::what
; this simply means that CustomException::what
promises not to modify exc
, but other code might.
C ++常见问题有关于 const方法。
The C++ FAQ has a bit more information on const methods.
这篇关于g ++:const丢弃限定符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!