18

为 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 库中,我假设有任何特殊的理由不这样做。如上所述,超载 << 有哪些风险/不便?

4

4 回答 4

11

If the << operator is included in the Qt library every client of the library will have to use the exact same implementation. But due to the nature of QString it is far from obvious this is what these clients want. Some people writing software interacting with legacy file in western europe may want to use Latin1() characters, US people may go with Ascii() and more modern software may want to use Utf8().

Having a single implementation in the library would restrict unacceptably what can be done with the whole library.

于 2013-04-29T14:53:16.380 回答
11

不需要实现这样的东西,只要有这样一个方便的解决方案,涉及QTextStream

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

QTextStream非常强大...

于 2016-07-19T12:48:37.367 回答
2

接受的答案指出了为什么没有operator<<功能的一些正当理由QString

通过提供一些便利功能并在特定应用程序中维护一些状态,可以轻松克服这些原因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
于 2017-04-06T06:07:30.887 回答
1

我认为在Qt library. 这里可能出现的唯一问题是std::ostream对象可能会修改传递给std::ostream::operator<<函数的参数的内容。

但是,在参考文献中明确指出,如果传递字符串缓冲区,此函数将修改参数 - 其他类型没有任何内容,所以我猜(常识告诉我) operator<< 不会修改char*范围。此外,在页面上没有关于修改传递的对象的内容。

QString::toAscii().constData()最后一件事:你可以使用QString::toStdString()orqPrintable(const QString&)宏而不是 using 。

于 2013-04-29T14:34:06.593 回答