从C++中定义的异常返回整数

Com*_*ost 2 c++ c++11

我想定义一个返回int的异常.我的代码如下.它显示错误.

class BadLengthException : public exception {
    public:
        int x;

    BadLengthException(int n){
        x =n;
    }

    virtual const int what() const throw ()  {
        return x;
    }
};
Run Code Online (Sandbox Code Playgroud)

错误是:

solution.cc:12:22:错误:为'virtual const int指定的冲突返回类型BadLengthException :: what()const'virtual const int what()const throw(){^ ~~~包含在/ usr/include中的文件/ c ++/7/exception:38:0,来自/ usr/include/c ++/7/ios:39,来自/ usr/include/c ++/7/ostream:38,来自/ usr/include/c ++/7/iostream :39,from solution.cc:1:/usr/include/c++/7/bits/exception.h:69:5:错误:覆盖'virtual const char*std :: exception :: what()const'what( )const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT;

Rem*_*eau 6

exception::what()返回一个const char*,你不能改变它.但您可以定义另一种方法来返回int,例如:

class BadLengthException : public std::length_error {
private:
    int x;
public:
    BadLengthException(int n) : std::length_error("bad length"), x(n) { }
    int getLength() const { return x; }
};
Run Code Online (Sandbox Code Playgroud)

然后在你的catch陈述中调用它,例如:

catch (const BadLengthException &e) {
    int length = e.getLength();
    ...
} 
Run Code Online (Sandbox Code Playgroud)