cpp-类型转换

    技术2026-01-26  10

    C的类型转换(type)变量 缺点不进行严格的类型判断

    c++类型转换

    1.static_cast 内置类型,具有继承关系的类指针和引用

    #include <iostream> using namespace std; class Animal{}; class Cat:public Animal{}; int main(){ int a = 97; a = static_cast<char>(a); cout << a << endl; Animal *a1; a1 = static_cast<Cat*>(a1); Animal a2; Animal& a21 = a2; a21 = static_cast<Cat&>(a2); return 0; }

    2.dynamic_cast 子类转父类

    #include <iostream> using namespace std; class Animal{}; class Cat:public Animal{}; int main(){ Cat *c1 = NULL; Animal *a1 = NULL; a1 = dynamic_cast<Animal*>(c1); Cat c2; Cat& c21 = c2; Animal a2; a2 = dynamic_cast<Animal&>(c21); return 0; }

    3.const_cast 增加/删除类型const

    #include <iostream> using namespace std; class Animal{}; class Cat:public Animal{}; int main(){ const Cat *c1 = NULL; Cat *c11 = const_cast<Cat *>(c1);//删除const c1 = const_cast<const Cat *>(c11);//增加const return 0; }

    4.reinterpret_cast 强制类型转换

    #include <iostream> using namespace std; class Animal{}; class Cat{}; typedef int(*FUNC2)(); typedef int(*FUNC1)(); int main(){ Animal *a1 =NULL; Cat *c1 =NULL; c1 = reinterpret_cast<Cat*>(a1); //函数指针转换 FUNC2 f2 =NULL; FUNC1 f1 =NULL; f1 = reinterpret_cast<FUNC1>(f2); return 0; }

    请考虑转换后的后果

    Processed: 0.026, SQL: 9