C++类型转换

static_cast(编译阶段)

  • 用于类型相关的指针之间相互转换
  • 用于基本类型的数据之间进行类型转换
#include class Base { public: int a; }; class Derived : public Base { public: int b; }; int main() { Derived *p1 = new Derived(); Base *p2 = static_cast(p1); Base *p3 = new Base(); Derived *p4 = static_cast(p3); int aa = 10; double bb = static_cast(aa); double cc = 3.14f; int dd = static_cast(cc); }

dynamic_cast(运行阶段)
  • 运行阶段执行类型检查
#include using namespace std; class Fish { public: virtual void swim() { cout << "Fish swim in water" << endl; }virtual ~Fish() {} }; class Tuna : public Fish { public: void swim() { cout << "tuna swims real fast in the sea" << endl; } }; class Carp : public Fish { public: void swim() { cout << "carp swims real slow in the lake" << endl; } }; void DetectFishType(Fish *fish) { Tuna* p1 = dynamic_cast(fish); if (p1) p1->swim(); Carp* p2 = dynamic_cast(fish); if (p2) p2->swim(); }int main() { Tuna tuna; Carp carp; DetectFishType(&tuna); DetectFishType(&carp); }

reinterpret_cast
  • 能够让程序员能够将一种对象类型转换为另一种

【C++类型转换】应尽量避免在应用程序中使用reinterpret_cast,因为它让编译器将类型X视为不相关的类型Y,这看起来不像是优秀的设计或实现。
const_cast
  • 让程序员能够关闭对象的访问修饰符const
    使用场景:拿到一个const引用的对象,通过这个对象操作非const的成员函数,编译器会报错,为了解决这个错误,需要使用到const_cast解除对象的const访问修饰符
#include using namespace std; class A { public: void print() { cout << "A print" << endl; } }; void printAllData(const A& a) { A& ra = const_cast(a); ra.print(); }int main() { A a; printAllData(a); return 0; }

    推荐阅读