从 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:错误:覆盖"虚拟" const char* std::exception::what(( const' 什么(( 常量 _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT;

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; }
};

然后在您的catch语句中调用它,例如:

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

嘿,我认为您正在 hackerrank 上做继承的代码,我遇到了同样的问题,我们也无法更改代码的另一部分,所以我们必须覆盖 what 函数,

对于您的C++ 11:

现在我们有 int n,但我们必须将其转换为 char* 才能返回它,

首先用 to_string(( 将其转换为字符串 然后使用 .c_str(( 将其设为常量 shar*(又名 C 字符串(

我们的班级现在变成:

class BadLengthException : public exception{
public:
string str;
BadLengthException(int n){
str = to_string(n);
}
const char * what () const throw() {
return str.c_str() ;
}
};

最新更新