为什么我会收到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
Run Code Online (Sandbox Code Playgroud)
在下面的代码示例中
#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'; }
};
Run Code Online (Sandbox Code Playgroud)
在讨论类似问题之前,我已经搜索过SOF.
我已经const在每个可能的地方添加了一个.
请赐教 - 我不明白......
编辑:这是在Ubuntu-Carmic-32bit上重现的步骤(g ++ v4.4.1)
customExc.cppmake customExc.o编辑:错误与CustomException.这堂课Foo与它无关.所以我删除了它.
Jos*_*ley 14
CustomException::what电话CustomException::code. CustomException::what是一个const方法,由const 后面 表示what().由于它是一个const方法,它不能做任何可能修改自身的事情. CustomException::code不是一个常量方法,这意味着,它并不能保证不修改本身.所以CustomException::what不能打电话CustomException::code.
请注意,const方法不一定与const实例相关. Foo::bar可以将其exc变量声明为非const并调用const方法,如CustomException::what; 这只是意味着CustomException::what承诺不会修改exc,但其他代码可能.
C++ FAQ提供了有关const方法的更多信息.
| 归档时间: |
|
| 查看次数: |
21667 次 |
| 最近记录: |