[英]g++: const discards qualifiers
why do I get a discard qualifiers
error: 为什么我会得到discard qualifiers
错误:
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
on the following code example 在下面的代码示例中
#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'; }
};
I have searched around on SOF before regarding simular issues. 在讨论类似问题之前,我已经搜索过SOF。
I have already added a const
on every possible place. 我已经在每个可能的地方添加了一个const
。
Please enlighten me - I don't get the point... 请赐教 - 我不明白......
EDIT : here are the steps to reproduce on Ubuntu-Carmic-32bit (g++ v4.4.1) 编辑 :这是在Ubuntu-Carmic-32bit上重现的步骤(g ++ v4.4.1)
customExc.cpp
将示例另存为customExc.cpp
make customExc.o
键入make customExc.o
EDIT : The error is related to CustomException
. 编辑 :错误与CustomException
有关。 The class Foo
has nothing to do with it. Foo
类与它无关。 So I have deleted it. 所以我删除了它。
CustomException::what
calls CustomException::code
. CustomException::what
调用CustomException::code
。 CustomException::what
is a const method, as signified by the const after what()
. CustomException::what
是const方法,由const 后面的const表示what()
。 Since it is a const method, it cannot do anything that may modify itself. 由于它是一个const方法,它不能做任何可能修改自身的事情。 CustomException::code
is not a const method, which means that it does not promise to not modify itself. CustomException::code
是不是一个const方法,这意味着它不承诺不修改本身。 So CustomException::what
can't call CustomException::code
. 所以CustomException::what
不能调用CustomException::code
。
Note that const methods are not necessarily related to const instances. 请注意,const方法不一定与const实例相关。 Foo::bar
can declare its exc
variable as non-const and call const methods like CustomException::what
; Foo::bar
可以将其exc
变量声明为非const,并调用const方法,如CustomException::what
; this simply means that CustomException::what
promises not to modify exc
, but other code might. 这只是意味着CustomException::what
承诺不修改exc
,但其他代码可能。
The C++ FAQ has a bit more information on const methods . C ++ FAQ提供了有关const方法的更多信息。
int code() const { return 42; }
Your what()
is a const member function, but code()
is not. 你的what()
是一个const成员函数,但code()
不是。
Just change code()
to code() const
. 只需将code()
更改为code() const
。
Your code()
member function is not declared const
. 您的code()
成员函数未声明为const
。 Calling non-const member functions from const member functions ( what()
in this case) is illegal. 从const成员函数调用非const成员函数(在本例中为what()
)是非法的。
Make your code()
member const. 使你的code()
成员const。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.