我有一个继承自 std::runtime_error
的类,如下所示:
#include <string>
#include <stdexcept>
class SomeEx : public std::runtime_error
{
public:
SomeEx(const std::string& msg) : runtime_error(msg) { }
};
所述 msg
将始终类似于“无效类型 ID 43”。有什么方法可以用另一个构造函数(或另一种方法)构建那个“what string”,以便我只提供整数类型 ID?像这样的东西:
SomeEx(unsigned int id) {
// set what string to ("invalid type ID " + id)
}
最佳答案
static std::string get_message(unsigned int id) {
std::stringstream ss;
ss << "invalid type ID " << id;
return ss.str();
}
SomeEx(unsigned int id)
: runtime_error(get_message(id))
{}
无关:我们有字符串 .what()
的原因是为了让人们停止使用错误数字。
关于c++ - 如何修改 C++ runtime_error 的 what 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9267674/