c++ - 从 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;
解决方案
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();
...
}
推荐阅读
- flutter - 如何动态更改 SliverAppBar 高度
- assembly - 组装 - 我哪里出错了?
- python - 带有硒的软件给出断言python3
- javascript - 使用 remove 功能同时删除两个 li
- c# - 选择名称相似但密码不同的用户
- android - 如何保持我的应用程序跟踪时间,在特定时间执行特定操作
- jdbc - kafka 连接转换
- email - Google Analytics - 跟踪电子邮件 - 使用 Gmail 客户端发送两次“打开”事件
- angularjs - 如何将数据从 ng-repeat 绑定到按钮的 onclick
- javascript - asp.net如何在控制器动作中访问ajax调用数据