c++ - ‘virtual char std::ctype<wchar_t>::do_narrow(wchar_t, char) const’ protected

标签 c++ locale facet

我正在尝试使用语言环境方面将 wstring 转换为字符串,但我遇到了以下错误:

test_facet.cpp: In function ‘int main()’:
test_facet.cpp:14: error: invalid initialization of reference of type ‘std::ctype<wchar_t>&’ from expression of type ‘const std::ctype<wchar_t>’
/usr/include/c++/4.4/bits/locale_facets.h:1430: error: ‘virtual char std::ctype<wchar_t>::do_narrow(wchar_t, char) const’ is protected
test_facet.cpp:16: error: within this context

来源:

#include <iostream>
#include <string>
#include <locale>
#include <algorithm>

using namespace std;

int main()
{
 locale loc("");
 std::wstring Str = L"ěščřžýáíé";
 std::string Str2;
 ctype<wchar_t> &ct = std::use_facet<std::ctype<wchar_t> >(loc);
 for(std::wstring::const_iterator It = Str.begin(); It < Str.end(); ++It)
   ct.do_narrow(*It, 'X' );
 std::cout << Str2 <<std::endl;
}

谁能告诉我,我做错了什么?

谢谢

最佳答案

2 件事:

1) use_facet 返回对 const 的引用,因此您不能将其分配给非 const 引用。所以将 ct 声明为:

 const ctype<wchar_t> &ct = ....

2) 如第二条错误消息所述,do_narrow 受到保护,外部调用者无法访问它。请改用 narrow,它是公开的。

关于c++ - ‘virtual char std::ctype<wchar_t>::do_narrow(wchar_t, char) const’ protected ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4271163/

相关文章:

c++ - 如何实现 Floyd 算法在具有矩形障碍物的 11x11 网格上寻找最短路径?

javascript - 显示索非亚当前本地时间(小时): Minutes 24h format

Android:在没有 "kn"语言环境的手机中显示卡纳达语

删除 ggplot 分面图中的一些轴标签

elasticsearch - 使用 elasticsearch 计算不同的值

c++ - 基于 CRTP 的解决方案会是什么样子?

c++ - 为什么 Visual C++ 无法编译继承自私有(private)嵌套类的友元模板?

c++ - 检查 1/n 小数点后是否有无限位数

swift - 获取语​​言环境日期格式信息

ruby-on-rails - 如何阻止 ThinkingSphinx 查询数据库以分面 MVA 字段?