【问题标题】:Override bad_alloc Exception覆盖 bad_alloc 异常
【发布时间】:2013-11-19 17:17:29
【问题描述】:

我正在尝试更改bad_alloc 的消息。

#include <iostream>
#include <iomanip>
#include <stdexcept>

using std::logic_error;
using std::bad_alloc;


class OutOfRange : public logic_error {
   public:
      OutOfRange(): logic_error("Bad pointer") {}
};


class OutOfMem : public bad_alloc {
   public:
      OutOfMem(): bad_alloc("not enough memory") {}
};

OutOfRange() 工作正常,但 OutOfMem 向我发送错误消息:

没有匹配函数调用std::bad_alloc::bad_alloc(const char[21])

【问题讨论】:

    标签: exception


    【解决方案1】:

    编译错误告诉你 bad_alloc 构造函数不接受 char *。 例如See here
    相反,请注意异常 what 方法是虚拟的,请改用它。

       class OutOfMem : public bad_alloc {
          public:
             OutOfMem() {}
             const char *what() const {
                 return "not enough memory";
             }
       };
    

    编辑:请注意,您可能必须声明它不会抛出如下:

     //... as before
     virtual const char * what() const throw () {
         return "not enough memory";
     }
     // as before ...
    

    【讨论】:

    • 我试了一下,它向我发送了一个错误,用于 `virtual const char* OutOfMem::what() const' 的更宽松的抛出说明符
    • what 是如何在您的设置中的 std::exception 中定义的?它有抛出说明符吗?
    • 好吧,我的头文件只有这个 #include #include #include using std::logic_error;使用 std::bad_alloc;
    • 解决方案将取决于您使用的(我认为是 gcc 的)版本,请参见此处:stackoverflow.com/questions/4282578/…
    猜你喜欢
    • 2012-02-13
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 2019-06-22
    相关资源
    最近更新 更多