1 静态类型转换和强制类型转换
1 static_cast reinterpret_cast
#include<iostream>
using namespace std;
void main() {
double dpi = 3.1415926;
int num1 = (int)dpi; //C类型转换
int num2 = static_cast<int>(dpi); //静态类型转换 编译时C++编译器会做类型检查
int num3 = dpi; //C语言中隐式类型转换均可使用static_cast<>()
// char * ===> int *
char* p1 = (char *)"hello...itcast";
int* p2 = NULL;
// p2 = static_cast<int*>p1; // 使用static_cast<>()编译器编译时会做类型检查 若有错误提示错误
p2 = reinterpret_cast<int*>(p1);
cout << "p1:" << p1 << endl;
cout << "p2:" << p2 << endl;
// 通过 static_cast<>() 和 reinterpret_cast<>() 实现C语言强制类型转换
}
结果
p1:hello...itcast
p2:006D9B30
2 dynamic_cast
动态类型转换,安全的基类和子类之间转换;运行时类型检查
#include<iostream>
using namespace std;
class Tree {};
class Animal {
public:
virtual void cry() = 0;
};
class Dog :public Animal{
public:
void cry() {
cout << "wangwang" << endl;
}
void athome() {
cout << "at home" << endl;
}
};
class Cat :public Animal {
public:
void cry() {
cout << "miaomiao" << endl;
}
void catch_mouse() {
cout << "catch_mouse" << endl;
}
};
void objplay(Animal *base) {
base->cry(); // 1继承 2 虚函数重写 3 父类指针 指向子类对象==>多态
// 能识别子类对象
// dynamic_cast 运行时类型识别 RIIT
Dog* pdog = dynamic_cast<Dog*>(base);
if (pdog != NULL) {
pdog->athome(); //特定类任务
}
Cat* pcat = dynamic_cast<Cat*>(base); //父类对象 ===> 子类对象 向下转型
if (pcat != NULL) {
pcat->catch_mouse();//特定类任务
}
}
void main() {
Dog d1;
Cat c1;
Animal* pBase = NULL;
pBase = &d1;
pBase = static_cast<Animal*>(&d1);
// 强制类型转换
pBase = reinterpret_cast<Animal*>(&d1);
{
Tree t1;
// pBase = static_cast<Animal*>(&t1); //C++编译器会做类型检查 报错
// 强制类型转换
pBase = reinterpret_cast<Animal*>(&t1);// 重新解释、强制类型转换
}
//
objplay(&d1);
objplay(&c1);
}
结果
wangwang
at home
miaomiao
catch_mouse
3 const_cast
去除变量只读属性
#include<iostream>
using namespace std;
// const char *p 让p指向的内存空间变成只读属性
void printBuf(const char* p) {
//p[0] = 'z';
char* p1 = NULL;
//const char*==>char * 把只读属性去掉
p1 = const_cast<char*>(p);
p1[0] = 'Z';
cout << p << endl;
}
void main() {
char buf[] = "abdfefadf";
// char* myp = "asdfasdasfasf";
// 要确保p指向的内存空间确实可以修改,不然产生意想不到的后果
// printBuf(myp);
printBuf(buf);
}
结果
Zbdfefadf