【问题标题】:c++ objected oriented programming exception failurec++面向对象编程异常失败
【发布时间】:2015-03-23 23:50:57
【问题描述】:

所以我正在使用“异常”库的继承创建一个异常,但我收到一个错误,上面写着“虚拟”的抛出更宽松。

#include <string>
#include <exception>
#include <sstream>

namespace Vehicle_Renting{

using namespace std;

class Auto_Rent_Exception : public std::exception{


protected:
      string error;

   public:
      Auto_Rent_Exception(){
      }
  virtual const string what() = 0;

  virtual Auto_Rent_Exception* clone() = 0;
};

它说:错误:'virtual Vehicle_Renting::Auto_Rent_Exception::~Auto_Rent_Exception()' 的更宽松的抛出说明符 Vehicle_Renting 是我项目的命名空间。

【问题讨论】:

  • 我们是否应该重新开始,看看谁先猜出您使用的工具链和语言版本?
  • 我正在使用 Code Blocks 编译器和 c99 标准。
  • c99 ?嗯.. 这是 C++ 代码,对吧? CodeBlocks 不是编译器,它是 IDE。你用的是什么编译器?克++?铿锵++,明威?什么版本?在上面代码中的哪个 specific 行上出现了这个错误? (用评论标记它)。事实上,一个可重现的案例会很有帮助,(works here)。
  • 哦,对不起,我的意思是 mingw 版本 4.4.1
  • 准确的错误信息怎么样?

标签: c++ oop exception inheritance virtual


【解决方案1】:

将原型析构函数添加到 Auto_Rent_Exception 的派生类中。

virtual ~Auto_Rent_Exception() throw();

附带说明,您应该小心在异常类中使用std::string(或任何动态分配内存的东西)。如果某些 API 函数失败(例如,因为剩余的内存太少),您的 std::string 构造函数可能会抛出 std::bad_alloc,隐藏初始异常。或者,如果您实现自己的内存分配器,您可能会创建一个无限循环的异常。最好捕获并忽略来自std::string 的异常,以便传播原始异常(没有描述,但总比没有/“错误”异常好)。

【讨论】:

    猜你喜欢
    • 2015-02-12
    • 1970-01-01
    • 2012-01-24
    • 2011-04-16
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多