reinterpret_cast强制类型转换符
用法:
new_type a = reinterpret_cast <new_type> (value)
将value的值转成new_type类型的值,a和value的值一模一样。比特位不变
reinterpret_cast用在任意指针(或引用)类型之间的转换;以及指针与足够大的整数类型之间的转换;从整数类型(包括枚举类型)到指针类型,无视大小。
需要注意的是:reinterpret_cast(yyy),xx与yyy必须有一个值为指针类型。
string 和 char[ ],char * 相互转换
例1
从char型数组中读取部分值到string类型的变量中:
string country ;
const char *section;
country = std::string(reinterpret_cast<const char*>(§ion[3],length));
例2
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main(){
string s = "hello,world";
char chrs[11];
strcpy_s(chrs, 11, s.c_str());//注意,string转化为char[]的时候,默认的字符串背后有'\0'标志;
cout << chrs << endl;
//const char* chr=s.c_str();
char c_s[6] = {'a','b','c','d','e','\0'};
string ss = c_s;
cout << ss << endl;
return 0;
}
---------------------
作者:阿华Go
来源:优快云
原文:https://blog.youkuaiyun.com/u014038273/article/details/77649525
版权声明:本文为博主原创文章,转载请附上博文链接!
PS. strcpy_s
strcpy_s包含在头文件<string.h>中,亲测也可,反正就改个名,其定义如下:
_ACRTIMP errno_t __cdecl strcpy_s(
Out_writes_z(_SizeInBytes) char* _Destination,
In rsize_t _SizeInBytes,
In_z char const* _Source
);
第一个参数:目标字符串指针
第二个参数:字符串长度,可使用strlen()函数直接求出,切记,在使用strlen()求出字符串长度时,勿忘+1
第三个参数:输入字符串指针
实例如下:
StringBad::StringBad(const char * s)
{
len = strlen(s); //计算字符串长度
str = new char[len + 1]; //分配存储空间
strcpy_s(str, len+1,s); //将s中字符串复制到str,最后一个空间为'\0'结束符
num_strings++;
cout << num_strings << ": \"" << str << "\" object created" << endl;