g++: const 丢弃限定符 [英] g++: const discards qualifiers

查看:38
本文介绍了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)

  1. 将示例另存为 customExc.cpp
  2. 输入 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 丢弃限定符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆