ToStdWStringAndBuiltInWchar/zh

From Qt Wiki
< ToStdWStringAndBuiltInWchar
Revision as of 17:05, 3 March 2015 by AutoSpider (talk | contribs) (Add "cleanup" tag)
Jump to navigation Jump to search
This article may require cleanup to meet the Qt Wiki's quality standards. Reason: Auto-imported from ExpressionEngine.
Please improve this article if you can. Remove the {{cleanup}} tag and add this page to Updated pages list after it's clean.

简体中文 English

QString、std::wstring 与内置的 wchar_t

问题陈述

Qt 建议我们构建基于Qt的软件时,像Qt库自身一样,不要将 wchar_t 作为内置类型。在一些情况下,这不是所期待的,或者是不可能的,因为其他的库构建时可能已经将 wchar_t 作为了内置类型。当使用 std::wstring、QString::toStdWString()和 QString::fromStdWString() 将导致链接错误.

可能的解决方案

Windows 使用 utf-16 作为本身字符的编码,Qt也是如此。借助这个信息我们可以使用下面的代码来规避这个问题:

/*! Convert a QString to an std::wstring */
std::wstring qToStdWString(const QString &amp;str)
{
#ifdef _MSC_VER
 return std::wstring((const wchar_t''')str.utf16());
#else
 return str.toStdWString();
#endif
}

/*! Convert an std::wstring to a QString */
QString stdWToQString(const std::wstring &amp;str)
{
#ifdef _MSC_VER
 return QString::fromUtf16((const ushort''')str.c_str());
#else
 return QString::fromStdWString(str);
#endif
}

注意 std::wstring 在其他平台下可能使用 uint32 (对于ucs-4/utf-32) 来实现。