#include <iostream> using namespace std; struct A { virtual void func() { cout << "A func" << endl; } }; struct B :public A { void func() { cout << "B func" << endl; } }; int main() { cout << "C++ 类型转换:static_cast,const_cast,dynamic_cast,reinterpret_cast" << endl; // static_cast(数据类型之间转换) float num1 = 2.9; int num2 = static_cast<int>(num1); cout << "static_cast float: " << num1 << endl; cout << "static_cast int: " << num2 << endl; cout << endl; // const_cast(去长量化) int data1 = 10; const int* data2 = &data1; int* data3 = const_cast<int*>(data2); cout << "const_cast data3: " << *data3 << endl; cout << endl; // dynamic_cast(将父类的指针或引用转换为子类的指针或引用,父类必须要有虚函数) B b; b.func(); A* a = dynamic_cast<A*>(&b); a->func(); B* bb = dynamic_cast<B*>(a); bb->func(); cout << endl; // reinterpret_cast(啥都行,但是不推荐) int n1 = 10; int* n2 = &n1; float* n3 = reinterpret_cast<float*>(n2); cout << "reinterpret_cast float: " << *n3 << endl; return 0; }
标签:类型转换,const,cout,dynamic,cast,static,func From: https://www.cnblogs.com/shiyixirui/p/18132567