TYPE B = static_case(TYPE)(a)
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*等
- 子类指针/引用与 父类指针/引用 转换。
我们拿虚函数那个例子改一下,如果我们不使用虚函数,想要调用子类的test111,可以把对象强转为child1 。
先把test111的virtual去掉
void test111() {
cout << "parent2" << endl;
}
强转类型
parent2* cd2 = new child1();
cd2->test111();
child1 *cd3 = static_cast<child1*>(cd2);
cd3->test111();
看下结果:
parent2
child
dynamic_cast
- 主要 将基类指针、引用 安全地转为派生类.
-
在运行期对可疑的转型操作进行安全检查,仅对多态有效
dynamic.png
可以看到,parent1不能转为child1,作为基类没有虚函数,会报错,我们加上一个虚函数
parent1 *p1 = new parent1;
child1 *c = dynamic_cast<child1*>(p1);
if (!c) {
cout << "转换失败" << endl;
}
parent2 *p2 = new parent2;
child1 *c = dynamic_cast<child1*>(p2);
if (c) {
cout << "转换成功" << endl;
}
对指针转换失败的得到NULL,对引用失败 抛出bad_cast异常
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;
网友评论