std :: ostream到QString?

时间:2015-06-19 01:11:56

标签: 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;

现在我想把错误作为QStrings抛出并稍后捕获它们,所以我现在写一下:

throw(QString("Error in void Cat::eat(const Bird &bird): bird has negative weight"));

我的问题是我一直在超载运营商&lt;&lt;所以我可以将它与许多对象一起使用,例如Bird,所以我实际上写了:

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

有没有办法可以将它作为QString抛出?我希望能够写出类似的内容:

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

但这不起作用。我该怎么办?

2 个答案:

答案 0 :(得分:4)

您可以按如下方式使用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()));
//           ^^^^^^^^^^^^^^^^^^^^^^^^^^

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

答案 1 :(得分:2)

std::stringstream类可以从重载的<<运算符接收输入。使用此功能,结合将其值作为std::string传递的功能,您可以编写

#include <sstream>
#include <QtCore/QString>

int main() {
    int value=2;
    std::stringstream myError;
    myError << "Here is the beginning error text, and a Bird: " << value;
    throw(QString::fromStdString(myError.str()));
}