2013-04-29 125 views
11

這是有道理的實施< <爲QString的一樣:操作<<爲QString的

std::ostream& operator <<(std::ostream &stream,const QString &str) 
{ 
    stream << str.toAscii().constData(); //or: stream << str.toStdString(); //?? 
    return stream; 
} 

,而不是寫

stream << str.toAscii().constData(); 
代碼每次

但是,由於它不在標準的Qt庫中,我假設沒有這樣做的任何特殊原因。如上所述超載< <有什麼風險/不便?

+1

我不明白爲什麼它是有道理的使用str.toAscii()代替toLatin1()或toUtf8()或toLocal8Bit()? – fjardon 2013-04-29 14:35:15

+0

@fjardon - 沒有特別的理由:)你提到的任何一個我認爲會起作用。 – 2013-04-29 14:38:01

+1

他們在7位乾淨的字符串之外做了非常不同的事情。 – Yakk 2013-04-29 14:39:40

回答

8

如果<<運算符包含在Qt庫中,那麼庫的每個客戶端都必須使用完全相同的實現。但由於QString的性質,這些客戶需要的東西遠非明顯。一些編寫與西歐遺留文件交互的軟件的人可能想要使用Latin1()字符,美國人可能會使用Ascii(),更多現代軟件可能想使用Utf8()。

在庫中有一個單獨的實現會限制整個庫可以做什麼,這是無法接受的。

+0

謝謝,我想這是有道理的 - 我認爲它不是無法解決的位寬,但相同的位寬可以根據QString表示的基礎文本進行不同處理。但是,爲「知道什麼字符編碼映射到正確的位置」提供自己的實現是安全的。 – 2013-04-29 15:06:49

+0

是的,如果您知道您只會處理Ascii,您可以創建自己的操作員。 – fjardon 2013-04-29 16:25:12

1

我不認爲在Qt library中排除(也不包括)這個任何特殊的原因。唯一可能出現的問題是std::ostream對象可能會修改傳遞給std::ostream::operator<<函數的參數的內容。

但是,在reference中明確指出,如果傳遞字符串緩衝區,此函數將修改參數 - 其他類型沒有任何關係,所以我猜(和常識告訴我的)操作符< <將不會修改char*參數。此外,在this頁面上沒有任何關於修改傳遞的對象。

最後一件事:不是使用QString::toAscii().constData(),而是使用QString::toStdString()qPrintable(const QString&)宏。

4

這不是要實行這樣的事情,只要存在這樣一個方便的解決方案,涉及QTextStream

QString s; 
QTextStream out(&s); 
s << "Text 1"; 
s << "Text 2"; 
s << "And so on...."; 

QTextStream是相當強大...

+1

...除非你必須使用的接口當然需要'std :: ostream'。 – boycy 2017-10-13 09:09:07

1

The accepted answer指出一些正當的理由爲什麼QString沒有operator<<函數。

通過提供一些便利功能並在應用程序特定的namespace中維護某些狀態,可以輕鬆地克服這些原因。

#include <iostream> 
#include <QString> 

namespace MyApp 
{ 
    typedef char const* (*QStringInsertFunction)(QString const& s); 

    char const* use_toAscii(QString const& s) 
    { 
     return s.toAscii().constData(); 
    } 

    char const* use_toUtf8(QString const& s) 
    { 
     return s.toUtf8().constData(); 
    } 

    char const* use_toLatin1(QString const& s) 
    { 
     return s.toLatin1().constData(); 
    } 

    // Default function to use to insert a QString. 
    QStringInsertFunction insertFunction = use_toAscii; 

    std::ostream& operator<<(std::ostream& out, QStringInsertFunction fun) 
    { 
     insertFunction = fun; 
     return out; 
    } 

    std::ostream& operator<<(std::ostream& out, QString const& s) 
    { 
     return out << insertFunction(s); 
    } 
}; 

int main() 
{ 
    using namespace MyApp; 

    QString testQ("test-string"); 

    std::cout << use_toAscii << testQ << std::endl; 
    std::cout << use_toUtf8 << testQ << std::endl; 
    std::cout << use_toLatin1 << testQ << std::endl; 

    return 0; 
} 

輸出:

test-string 
test-string 
test-string