一、C类型转换
转换格式如下:
Type b = (Type)a
1
二、C++类型转换
1、const_cast
去掉类型的const或volatile属性。
const int a = 10;
a = 20; // compile error
int& b = const_cast<int&>(a);
b = 20; // compile ok,a==20,b==20
int a = 10;
const int *p = &a;
*p = 20; // compile error
int* pp = const_cast<int *>(p);
*pp = 20; // compile ok,a==20
const_cast<>里边的内容必须是引用或者指针。
2、static_cast
类似C风格的强制转换,进行无条件转换。
基本数据类型转换,enum,struct,int,char,float等
把任何类型的指针转换成void*。
基类和子类之间的转换:其中子类指针转换为父类指针是安全的,但父类指针转换为子类指针是不安全的(基类和子类之间的动态类型转换建议用dynamic_cast)。
static_cast不能去掉类型的const、volatile属性(用const_cast)。
// 基本数据类型转换
int n = 6;
double d = static_cast<double>(<