g++: const discards qualifiers(g++: const 丢弃限定符)
问题描述
为什么我会收到 discard 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.
请赐教-我不明白这一点...
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
EDIT:错误与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
调用 CustomException::code
.CustomException::what
是一个 const 方法,由 const after what()
表示.由于它是一个 const 方法,它不能做任何可能修改自身的事情.CustomException::code
不是 const 方法,这意味着它确实 not 承诺不会修改自己.所以 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
变量声明为非常量,并调用 CustomException::what
等 const 方法;这仅仅意味着 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 丢弃限定符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:g++: const 丢弃限定符
基础教程推荐
- C/C++编程中const的使用详解 2023-03-26
- C利用语言实现数据结构之队列 2022-11-22
- C++中的atoi 函数简介 2023-01-05
- C++使用easyX库实现三星环绕效果流程详解 2023-06-26
- 详解c# Emit技术 2023-03-25
- C语言基础全局变量与局部变量教程详解 2022-12-31
- C语言 structural body结构体详解用法 2022-12-06
- 如何C++使用模板特化功能 2023-03-05
- C++详细实现完整图书管理功能 2023-04-04
- 一文带你了解C++中的字符替换方法 2023-07-20