ToStdWStringAndBuiltInWchar/zh: Difference between revisions
Jump to navigation
Jump to search
AutoSpider (talk | contribs) (Decode HTML entity names) |
(Partial cleanup; abuse of categories for localization; removed from categories) |
||
Line 1: | Line 1: | ||
{{Cleanup | reason=Auto-imported from ExpressionEngine.}} | {{Cleanup | reason=Auto-imported from ExpressionEngine.}} | ||
{{LangSwitch}} | |||
[[Category:HowTo]] | [[Category:HowTo]] | ||
[[Category:snippets]] | [[Category:snippets]] | ||
= QString、std::wstring 与内置的 wchar_t = | = QString、std::wstring 与内置的 wchar_t = |
Revision as of 02:01, 25 May 2015
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. |
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 &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 &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) 来实现。