'virtual char std :: ctype <wchar_t> :: do_narrow(wchar_t,char)const'受保护</wchar_t>

时间:2010-11-24 20:21:47

标签: c++ locale facets

我正在尝试使用locale faces将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 个答案:

答案 0 :(得分:0)

您无法从此上下文调用do_narrow。只允许类ctype(和deriveds)的成员方法调用do_narrow。

答案 1 :(得分:0)

2件事:

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

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

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