从 C++ 中定义的异常返回整数
return integer from defined exception in 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() ;
}
};
- 从函数(不抛出函数)返回异常以进行消息格式化?
- C++ 返回异常,我应该释放资源吗?
- 当返回值丢失时,C++ 代码行为异常
- 从 C++ 中定义的异常返回整数
- 为什么访问模板化变体作为返回值抛出异常
- boost::create_directory 在发布模式下返回异常
- C :ScopeGuard vs返回支票和异常处理
- 动态指针引用数组由三元运算符返回值,但有异常
- 返回内存异常错误的矢量
- 通过引用从 c++ 函数异常返回对象是否安全
- 遇到异常时给定函数的返回值是多少
- c++运算符=工作异常(函数内部输出正常,但返回后错误)
- 在具有异常处理的函数中返回类
- Dynamic_cast何时返回0,什么时候引发异常?CPP
- 如何将枚举返回值转换为C 异常
- 带有循环和异常的返回语句
- 引发异常与返回代码
- 从可能引发异常的函数返回 std::string
- QApplication::notify()在捕获异常时应该返回什么
- C++异常返回类型为什么字符*