【发布时间】:2015-09-04 20:38:00
【问题描述】:
有没有办法将 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"));
我的问题是我一直在重载运算符 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));
但这不起作用。我该怎么办?
【问题讨论】:
-
尝试从你的字符串部分创建一个
std::stringstream,然后在QString的构造函数中使用ss.str()? IE。throw(QString(ss.str())); -
应该是
QString::fromStdString(ss.str())- 抱歉