1.static_cast基本类型转换
int main1() { //printf("%d", 10.2); //printf("%f", (float)1); //printf不会完成数据类型转换 //printf("%d", static_cast<int>(10.2)); //默认转换 printf("%f", static_cast<float >(1)); }
2.reinterpret_cast(指针类型转换)
int main2() { int *pint = new int(1); char *pch = reinterpret_cast<char*>(pint); //指针类型转换 i for(int i = 0; i < 4; i++) { //显示数据, cout << static_cast<int>(*(pch + i)) << " "<< reinterpret_cast<void*>(pch + i) << endl; } cin.get(); }
3.const_cast(const数据类型转换)
int main3() { int num[5] = {1, 2, 3, 4, 5}; const int *p = num; //int *pint =reinterpret_cast<cint*>(int*)(p); reinterpret_cast不适于const int *pint = const_cast<int*>(p); for(int i = 0; i < 5; i++) { cout << pint[i] << " " << reinterpret_cast<void*>(pint + i) << endl; } cin.get(); }
4.dynamic_cast(父类子类转换)
//父类 class huahua { public: int hua1; virtual void run() { cout << "huahua is running" << endl; } }; //子类 class xiaohua: public huahua { public: int xiaohua1; void run() override { cout << "xiaohuahua is playing" << endl; } }; int main() { huahua *pfu = new huahua; xiaohua *pzi = new xiaohua; //创建一个父类对象以及子类 pfu->run(); pzi->run(); // huahua *phua = dynamic_cast<huahua*>(pzi); //子类对象转换为父类指针 // cout << reinterpret_cast<void*>(phua) << endl; // phua->run(); xiaohua *pxiaohua = dynamic_cast<xiaohua*>(pfu); cout << reinterpret_cast<void*>(pxiaohua) << endl; if(pxiaohua != nullptr) { pxiaohua->hua1 = 10; //访问子类继承父类对象的变量 pxiaohua->xiaohua1 = 10; pxiaohua->run(); //子类的对象 (*pxiaohua).huahua::run(); //子类中间父类的方法 } }