类型转换
- const_cast : 修改类型的const或volatile属性
- static_cast :
- 基础类型之间互转。如:float转成int、int转成unsigned int等
- 指针与void之间互转。如:float*转成void*、Bean*转成void*、函数指针转成void*等
- 子类指针/引用 与 父类指针/引用 转换。
- dynamic_cast :
- 主要 将基类指针、引用 安全地转为派生类.
- 在运行期对可疑的转型操作进行安全检查,仅对多态有效
- reinterpret_cast: 对指针、引用进行原始转换
const_cast
修改类型的const或volatile属性
const char *a;
char *b = const_cast<char*>(a);
char *a;
const char *b = const_cast<const char*>(a);
static_cast
- 基础类型之间互转。如:float转成int、int转成unsigned int等
- 指针与void之间互转。如:float*转成void*、Bean*转成void*、函数指针转成void*等
- 子类指针/引用与 父类指针/引用 转换。
class Parent {
public:
void test() {
cout << "p" << endl;
}
};
class Child :public Parent{
public:
void test() {
cout << "c" << endl;
}
};
Parent *p = new Parent;
Child *c = static_cast<Child*>(p);
//输出c
c->test();
//Parent test加上 virtual 输出 p
dynamic_cast
主要 将基类指针、引用 安全地转为派生类.
在运行期对可疑的转型操作进行安全检查,仅对多态有效
//基类至少有一个虚函数
//对指针转换失败的得到NULL,对引用失败 抛出bad_cast异常
Parent *p = new Parent;
Child *c = dynamic_cast<Child*>(p);
if (!c) {
cout << "转换失败" << endl;
}
Parent *p = new Child;
Child *c = dynamic_cast<Child*>(p);
if (c) {
cout << "转换成功" << endl;
}
reinterpret_cast
对指针、引用进行原始转换
float i = 10;
//&i float指针,指向一个地址,转换为int类型,j就是这个地址
int j = reinterpret_cast<int>(&i);
cout << hex << &i << endl;
cout << hex << j << endl;
cout<<hex<<i<<endl; //输出十六进制数
cout<<oct<<i<<endl; //输出八进制数
cout<<dec<<i<<endl; //输出十进制数
char*与int转换
//char* 转int float
int i = atoi("1");
float f = atof("1.1f");
cout << i << endl;
cout << f << endl;
//int 转 char*
char c[10];
//10进制
itoa(100, c,10);
cout << c << endl;
//int 转 char*
char c1[10];
sprintf(c1, "%d", 100);
cout << c1 << endl;