我有一个继承自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”。有没有办法用另一个构造函数(或另一个方法)构建“什么字符串”,以便我只提供整数类型ID?类似的东西:
SomeEx(unsigned int id) {
// set what string to ("invalid type ID " + id)
}
答案 0 :(得分:5)
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()
的原因是人们停止使用错误号码。
答案 1 :(得分:2)
当然:SomeEx(unsigned int id) : runtime_error(std::to_string(id)) { }
答案 2 :(得分:0)
如果您可以将数字转换为字符串,则可以简单地附加它们:
#include <string>
#include <stdexcept>
std::string BuildMessage(std::string const& msg, int x)
{
std::string result(msg);
// Build your string here
return result;
}
class SomeEx : public std::runtime_error
{
public:
SomeEx(const std::string& msg)
: runtime_error(BuildMessage(msg, id)) { }
};
答案 3 :(得分:0)
添加到Mooing Duck的答案,现在你可以使用lambda并直接调用它:
SomeEx(unsigned int id) :
std::runtime_error {
[](const auto id) {
std::ostringstream ss;
ss << "invalid type ID " << id;
return ss.str();
}(id)
}
{
}