覆盖bad_alloc异常

时间:2013-11-19 17:17:29

标签: exception

我正在尝试更改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])

时没有匹配功能

1 个答案:

答案 0 :(得分:2)

编译错误告诉您bad_alloc构造函数不接受char *。 例如See here
相反,请注意异常what方法是vritual并使用它。

   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 ...