首页 > 解决方案 > 从 C++ 中定义的异常返回整数

问题描述

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

class BadLengthException : public exception {
    public:
        int x;

    BadLengthException(int n){
        x =n;
    }

    virtual const int what() const throw ()  {
        return x;
    }
};

错误是:

解决方案.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,来自solution.cc:1:/usr/include/c++/7/bits/exception.h:69:5:错误:覆盖'virtual const char* std::exception::what() const'什么( ) 常量 _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT;

标签: c++c++11

解决方案


exception::what()返回 a 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; }
};

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

catch (const BadLengthException &e) {
    int length = e.getLength();
    ...
} 

推荐阅读