std :: exception子类,字符串成员变量

ale*_*lex 11 c++ string exception

以下代码工作得很好:

#include <exception>

using namespace std;

class FileException : public exception { // error occurs here
    int _error;
    // string _error; <-- this would cause the error
public:
    FileException(int error);
    // FileException(string error);
    const char* what() const throw();
};
Run Code Online (Sandbox Code Playgroud)

但是只要我将类型更改_error为字符串,就会发生以下编译错误:

覆盖函数的异常规范比基本版本更宽松

ken*_*ytm 23

的析构函数std::string不是不抛,这将导致隐含的析构函数FileException 无抛出无论是.但是析构函数std::exception是无抛出的,因此存在编译器错误.

您可以声明一个显式的无抛出析构函数:

virtual ~FileException() throw() {}
Run Code Online (Sandbox Code Playgroud)

或者只是继承std::runtime_error而不是std::exception,它有一个std::string输入的构造函数.


Mar*_*ork 6

简化:

// Derive from std::runtime_error rather than std::exception
// std::runtime_error (unlike std::exception) accepts a string as an argument that will
// be used as the error message.
//
// Note: Some versions of MSVC have a non standard std::exception that accepts a string
//       Do not rely on this.
class FileException : public std::runtime_error
{
public:
    // Pass error msg by const reference.
    FileException(std::string const& error)
        // Pass the error to the standard exception
        : std::runtime_error(error)
    {}
    // what() is defined in std::runtime_error to do what is correct
};
Run Code Online (Sandbox Code Playgroud)