我可以跨越重新解释的类型转换,并且在大多数情况下都会发出警告,因此我想知道是否还有其他选择(或者当然是重新解释的类型的干净实现)。
You don't say what warning was given or what the problem was, but casting to char*
with reinterpret_cast
should work without warnings:
unsigned char *a;
const char *b = reinterpret_cast<char*>(a);
It depends on what you're trying to do.
If you just want to access the contents as char
, then a simple static_cast
or using the value in a context where a char
is expected will do the trick.
If you need to pass the buffer to a function expecting a char const*
, a reinterpret_cast
is about the only solution.
If you want a string, using the pointers into the buffer will be fine:
std::string
bufferToString( unsigned char const* buffer, size_t length )
{
return std::string( buffer, buffer + length );
}
or you can copy into an existing string:
myString.assign( buffer, buffer + length );
myString.append( buffer, buffer + length );
// etc.
Any string function (or algorithm, like std::copy
) which takes two iterators can be used. All that is required is that dereferencing the iterator result in a type which converts implicitly to char
, which is the case of unsigned char
.
(You cannot use the string functions which take a buffer address and a length, as these are not templates, and require the buffer address to have type char const*
. And while unsigned char
converts implicitly to char
, unsigned char*
requires a reinterpret_cast
to convert it to char*
.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.