[英]std::ostream to QString?
有沒有辦法將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
,如下所示:
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
。
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()));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.