包含串联消息的 C++ 运行时错误

c++ runtime error with concatenated message

本文关键字:C++ 运行时错误 消息 包含串      更新时间:2023-10-16

我想在加载包含他的路径的位图时抛出错误

ALLEGRO_BITMAP* bitmap;
bitmap_path
if(bitmap=al_load_bitmap(bitmap_path)==0){
   throw runtime_error("error loading bitmap from: '"<<bitmap_path<<"'");
};
//continue if no error

不能使用 << 运算符直接连接字符串。

如果bitmap_pathstd:::string,请改用+运算符:

throw runtime_error("error loading bitmap from: '" + bitmap_path + "'");

如果 bitmap_pathchar*,请将其或第一个字符串文本转换为临时std::string,以便可以使用+

throw runtime_error("error loading bitmap from: '" + string(bitmap_path) + "'");

throw runtime_error(string("error loading bitmap from: '") + bitmap_path + "'");

否则,您可以使用 std::ostringstream 或等效项来构造临时std::string值:

ostringstream oss;
oss << "error loading bitmap from: '" << bitmap_path << "'";
throw runtime_error(oss.str());