c++ - 结构不接受 wchar_t

标签 c++ wchar-t

这是我唯一能想到的。这东西有知觉

我有一个结构如下:

struct NumPair
{
    wchar_t *pFirst, *pSecond;
    int count;

with ctor, copy assignment and construction as

NumPair( wchar_t *pfirst, wchar_t *psecond, int count = 0)
NumPair( const NumPair& np )
NumPair& operator=( const NumPair& np )

这是我上一个问题的扩展,在这个问题中,我要求一种方法来对字符指针列表进行排序,其中包含特殊(德语)字符,例如 ü、ä、ö

解决方案似乎是使用宽字符类型,但编译器出于某种原因抛出了一百多个转换错误。

示例输入:

// dict_ is a container of NumPairs.
dict_.push_back( NumPair ( "anfangen", "to begin, to start" ) );

编译器提示它无法将 const char * 转换为 wchar_t。很好,我将 push_back 改为 say

dict_.push_back( NumPair ( wchar_t("anfangen"), wchar_t("to begin, to start") ) );

编译器错误:找不到接受所有参数的 NumPair 构造函数。

什么。这。 hell 。我尝试了一个完整的重建,以为我的 VSC++10 搞砸了。不,我猜不是。

我做错了什么?

代码

构造函数、赋值和复制构造都是 wchar_t 指针的深度复制,如下所示。

包含 wchar.h。

NumPair( wchar_t *pfirst, wchar_t *psecond, int count = 0)
    : count(count)
{
    size_t s1, s2;
    s1 = wcslen(pfirst);
    s2 = wcslen(psecond);
    pFirst  = new wchar_t[s1];
    pSecond = new wchar_t[s2];
    wcscpy(pFirst, pfirst);
    wcscpy(pSecond, psecond);
}

最佳答案

主要有两个问题。

首先,wchar_t 的字符串字面量写成L"blah blah"(注意L)。

其次,const 正确性:像wchar_t const* pFirst 一样声明你的形式参数。这允许直接使用文字作为实际参数。或任何 const 字符串。

干杯,

关于c++ - 结构不接受 wchar_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4071522/

相关文章:

c++ - 使用多重继承进行转换

c++ - 为什么我的复制构造函数被删除了?

c++ - 如何记录接受回调的函数?

c++ - 在文本框中使用 WM_CHAR 输入处理的 gobbledygook

c++ - 重载 wstring 和 wchar_t 时的类似转换 *

c - 将 wscanf 用于 UTF-8 时不要忽略空格

c - asprintf 有 wchar_t 版本吗?

c++ - 释放 vector 的 wchar_t*

c - 使用 wsprintf 将 int 转换为 wchar_t*

c++ - 编译 range-v3 const 方法时出现编译错误