std::ostream 到 QString?

Seu*_*eub 5 c++ qt exception

有没有办法将 std::ostream 转换为 QString?

请允许我扩展一下它是否有用:我正在用 C++/Qt 编写一个程序,并且我曾经(不)仅使用 std::cout 来处理/调试异常,例如:

std::cout << "Error in void Cat::eat(const Bird &bird): bird has negative weight" << std::endl;
Run Code Online (Sandbox Code Playgroud)

现在我想将错误作为 QString 抛出并稍后捕获它们,所以我现在会写:

throw(QString("Error in void Cat::eat(const Bird &bird): bird has negative weight"));
Run Code Online (Sandbox Code Playgroud)

我的问题是我一直在重载运算符 << 以便我可以将它与许多对象一起使用,例如 a Bird,所以我实际上会写:

std::cout << "Error in void Cat::eat(const Bird &bird): bird " << bird << " has negative weight" << std::endl;
Run Code Online (Sandbox Code Playgroud)

现在有没有办法可以将其作为 QString 抛出?我希望能够写出类似的东西:

std::ostream out;
out << "Error in void Cat::eat(const Bird &bird): bird " << bird << " has negative weight" << std::endl;
throw(QString(out));
Run Code Online (Sandbox Code Playgroud)

但这行不通。我应该怎么办?

Sho*_*hoe 5

您可以std::stringstream按如下方式使用:

std::stringstream out;
//   ^^^^^^
out << "Error in void Cat::eat(const Bird &bird): bird " << bird << " has negative weight" << std::endl;
throw(QString::fromStdString(out.str()));
//           ^^^^^^^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

具体来说,std::stringstream::str成员函数将为您提供一个std::string,然后您可以将其传递给QString::fromStdString静态成员函数来创建一个QString.