utf8格式源代码中的字符串,默认都会当作char来处理,除非用L""符号来修饰

111 篇文章 9 订阅
在Qt5中,源代码中的字符串默认按char处理,但某些情况需使用L""修饰以匹配宽字符。如m_conn->put_HttpProxyAuthMethod(L"Basic"),不加L会导致编译错误。注意,某些函数如QString::compare不需要L""也能正确处理英文字符。Qt5假定执行字符集为UTF-8,确保C++执行字符集也是UTF-8以避免问题。
摘要由CSDN通过智能技术生成

   原先QString("mystrr"),现在都不认了,必须都要加上L才行

   原先:m_conn->put_HttpProxyAuthMethod("Basic");

   现在:m_conn->put_HttpProxyAuthMethod(L"Basic");

   同理:handle = m_conn->openFile(UUU(strRemote) ,L"writeOnly",L"createTruncate"); 原因是库函数强求

   前提:不使用VS2010开始的pragram指令

注意1

   if (m_conn->ProxyType=="WEBPROXY")  倒是不必改。加上L反而错误。

   原因是三个重载函数里,没有wchar_t*或者QChar*的比较:

bool    operator==(QLatin1String other) const
bool    operator==(const char * other) const
bool    operator==(const QByteArray & other) const

注意2

     InsertLog("debug", m_taskname, strAction, tr("try to reconnect again...")); 插入的日志没有问题,说明对标准英文字符自动转成Unicode没有问题。

    原因是,编译器以char*读取"debug"字符,但是没关系,在调用函数的时候,会自动调用

QString(const char * str)

   从而成功把它转化成了一个正确的QString。同时赏析一下所有构造函数:

QString()
QString(const QChar * unicode, int size = -1)
QString(QChar ch)
QString(int size, QChar ch)
QString(QLatin1String str)
QString(const QString & other)
QString(QString && other)
QString(const char * str)
QString(const QByteArray & ba)

   还是不明白,为什么InsertLog(L"debug")会编译通不过呢?

注意3

    strRemote += "/dir.case"; 为什么这样写?加上L反而错误。

   原因是9个重载函数里,没有wchar_t*或者QChar*的赋值(得注意,是QChar*,不是QChar):

QString &    operator+=(const QString & other)
QString &    operator+=(QChar ch)
QString &    operator+=(const QStringRef & str)
QString &    operator+=(QLatin1String str)
QString &    operator+=(const char * str)
QString &    operator+=(const QByteArray & ba)
QString &    operator+=(char ch)

理论解释

   Qt5假定的执行字符集是UTF8,不再允许用户擅自改动。这样一来,Qt4中setCodecXXX的各种副作用不再存在,而且中文问题更为简单。

QString s1 = "汉语";
QString s2("漢語");
QString s3 = tr("中文")
QString s4 = QStringLiteral("中文");//只要字符串不需要翻译,请关注这个
QString s5 = QString::fromWCharArray(L"中文");
QString s6 = u8"中文";//C++11
QString s7 = tr(u8"中文")
...

   所有这些在Qt5默认都会正常工作,唯一要求就是:确保你的C++的执行字符集(the execution character set)是UTF-8

   ·尽管 L"..."(wchar_t*) 在Windows下是UTF16,但是不具备跨平台性。

 

参考:

https://www.yuque.com/docs/share/27a0ed37-ad1b-41da-b354-c91ae93b85d1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值