gpt4 book ai didi

qt - 为什么QString用引号打印?

转载 作者:行者123 更新时间:2023-12-03 15:10:07 27 4
gpt4 key购买 nike

因此,当您使用qDebug()打印QString时,输出中会突然出现引号。

int main()
{
QString str = "hello world"; //Classic
qDebug() << str; //Output: "hello world"
//Expected Ouput: hello world
}

我知道我们可以使用 qPrintable(const QString)来解决此问题,但是我只是想知道 QString为什么那样工作?而且 QString内部是否有一种方法可以更改其打印方式?

最佳答案

为什么?
这是因为 qDebug() 的实现。
source code:

inline QDebug &operator<<(QChar t) { stream->ts << '\'' << t << '\''; return maybeSpace(); }
inline QDebug &operator<<(const char* t) { stream->ts << QString::fromAscii(t); return maybeSpace(); }
inline QDebug &operator<<(const QString & t) { stream->ts << '\"' << t << '\"'; return maybeSpace(); }
因此,
QChar a = 'H';
char b = 'H';
QString c = "Hello";

qDebug()<<a;
qDebug()<<b;
qDebug()<<c;
输出
'H' 
H
"Hello"

评论
那么为什么Qt这样做呢?由于 qDebug是用于调试的,因此各种类型的输入将成为通过 qDebug输出的文本流。
例如, qDebug将 bool(boolean) 值打印到文本表达式 true / false中:
inline QDebug &operator<<(bool t) { stream->ts << (t ? "true" : "false"); return maybeSpace(); }
它将 truefalse输出到您的终端。因此,如果您有一个存储 QStringtrue,则需要用引号 "来指定类型。

关于qt - 为什么QString用引号打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27976581/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com