引入:
C++ 有四种转型风格。
static_cast, dynamic_cast, const_cast, reinterpret_cast.
下面分别介绍日常用法。
1. static_cast
最常用的是 static_cast ,常用于 int 强转 double 型.
double b = (double)10 / 2; // C 风格。
double b = static_cast<double> (10) /20; // C++ 风格
C++风格比C风格多了个前缀,改成这样的好处是 只要全局搜索关键字“static_cast” 你就能立刻找到这句代码位置了。而 c 语言风格,搜关键字“double” 的话,就不好找了,太多了。
2. const_cast
const int c = 3;
int *b = static_cast<int*>( &c ) ; // 这是错误的转换会报错如下:
// error C2440: 'static_cast': cannot convert from 'const int *' to 'int *
改为const_cast
const int c = 3;
int* b = const_cast<int*>( &c ) ;
static_cast 的面子不够大啊,没法把固执的const转过来,只能让 const_cast 出马。
3. dynamic_cast
前两种可以向上转型,但是向下转型就不好使。
dynamic_cast 主要用在 C++ 中类之间的向下转型。
将 指向子类对象的父类指针 向下转型为 子类指针。
class animal { public:virtual ~animal() {} };
class dog :public animal {};
class cat :public animal {};
int test_dynamic_cast()
{
animal* a = new cat; //cat 向上转型 b 是父类指针 指向子类对象
dog* d = dynamic_cast<dog*> (a);//父类指针 向下转型,错误
(d != nullptr) ? std::cout << "success" << std::endl : std::cout << "cast failed" << std::endl;
cat* c = dynamic_cast<cat*> (a);//父类指针 向下转型,正确
(c != nullptr) ? std::cout << "success" << std::endl : std::cout << "cast failed" << std::endl;
return 0;
}
cat 先向上转为父类指针,然后父类向下转为 dog 是不行的,转型为 cat 是可以的。
4. reinterpret_cast
最自由的转换,简直是位面之子,当然,结果不保证对,一般会奔溃,所以一般没人会用这个。。。
int a = 2;
double* d= reinterpret_cast<double*> (a);