jac*_*hab 76 c++ casting const
我有:
unsigned char *foo();
std::string str;
str.append(static_cast<const char*>(foo()));
Run Code Online (Sandbox Code Playgroud)
错误: invalid static_cast from type ‘unsigned char*’ to type ‘const char*’
在C++风格中投射的正确方法是什么?
Bri*_*ndy 56
char *
并被const unsigned char *
认为是不相关的类型.所以你想要使用reinterpret_cast
.
但是如果你要从const unsigned char*
非const
类型转变,你需要先使用const_cast
.reinterpret_cast
不能抛弃const
或volatile
资格.
Jar*_*Par 51
尝试 reinterpret_cast
unsigned char *foo();
std::string str;
str.append(reinterpret_cast<const char*>(foo()));
Run Code Online (Sandbox Code Playgroud)
Rub*_*ink 46
reinterpret_cast的
AJG*_*AJG 17
unsigned char*基本上是一个字节数组,通常用于表示原始数据而不是字符串.unicode字符串将表示为wchar_t*
根据C++标准,unsigned char*和char*之间的reinterpret_cast是安全的,因为它们具有相同的大小并且具有相同的构造和约束.我总是试图避免reintrepret_cast比const_cast更多.
如果静态转换失败了你正在做的事情你可能想重新考虑你的设计,因为坦率地说,如果你使用的是C++,你可能想利用"plus plus"部分提供的东西并使用字符串类和STL(aka std :: basic_string可能对你更好)
太多的评论无法对不同的答案进行评论,所以我会在这里留下另一个答案。
你可以而且应该使用reinterpret_cast<>
,在你的情况下
str.append(reinterpret_cast<const char*>(foo()));
Run Code Online (Sandbox Code Playgroud)
因为,虽然这两个是不同的类型,但 2014 标准,章节3.9.1 Fundamental types [basic.fundamental]
说它们之间存在关系:
平原
char
,signed char
并unsigned char
有三种不同的类型,统称为窄字符类型。Achar
、 asigned char
和 anunsigned char
占用相同的存储量并具有相同的对齐要求(3.11);也就是说,它们具有相同的对象表示。
(选择是我的)
这是一个可用的链接:https : //en.cppreference.com/w/cpp/language/types#Character_types
使用wchar_t
:对Unicode /多字节字符串已经过时使用UTF-8的时候我应该使用wchar_t的?
归档时间: |
|
查看次数: |
105320 次 |
最近记录: |