- static_cast
- interpret_cast
- const_cast
- dynamic_cast
static_cast
#include <iostream>
using namespace std;
class A {
public:
operator int() {return 1;}
operator char*() {return NULL;}
};
int main() {
A a;
int n; char* p = "new Dragon Inn";
n = static_cast<int>(3.14); // n的值为3
n = static_cast<int>(a); // 调用a.operator int, n的值为1
p = static_cast<char*>(a); // 调用a.operator char* p的值为NULL
n = static_cast<int> (p); // 编译错误,static_cast不能将指针转换成整型
p = static_cast<char*>(n); // 编译错误
return 0;
}
reinterpret_cast
#include <iostream>
using namespace std;
class A {
public:
int i;
int j;
A(int n):i(n), j(n){}
};
int main() {
A a(100);
int & r = reinterpret_cast<int&>(a); // 强行让r引用a
r = 200; // 把a.i变成200
cout << a.i << "," << a.j << endl; // 输出200,100
int n = 300;
A * pa = reinterpret_cast<A*>(& n); // 强行让pa指向n
pa->i = 400; // n变成400
pa->j = 500; // 不安全,很可能崩溃
cout << n << endl; // 输出400
long long la = 0x12345678abcdLL;
pa = reinterpret_cast<A*>(la); // la太长,只能取低32为0x5678abcd拷贝给pa
// 在64位的机器上不行,因为指针是64位的,而unsigned int 是32位的
unsigned int u = reinterpret_cast<unsigned int>(pa); // pa逐个比特拷贝给u
cout << hex << u << endl; // 输出5678abcd
typedef void (* PF1)(int);
typedef int (* PF2)(int, char*);
PF1 pf1; PF2 pf2;
pf2 = reinterpret_cast<PF2>(pf1); // 两个不同类型的函数指针
}
const_cast
dynamic_cast
dynamic_cast是通过检查虚函数表的指针来判断该类是否为多态类的
#include <iostream>
#include <string>
using namespace std;
class Base {
public:
virtual Base() {}
};
class Derived: public Base {
};
int main() {
Base b;
Derived d;
Derived * pd;
pd = reinterpret_cast<Derived *>(&b);
if(pd == NULL) //此处pd不会为NULL。 reinterpret_cast不检查安全性,总是进行转换
// 不会执行
cout << "unsate interpret_cast" << endl;
pd = dynamic_cast<Derived *> (&b);
if(pd == NULL) //结果会是NULL,因为 &b不是指向派生类对象,此转换不安全
cout << "unsafe dynamic_cast1" << endl; // 会执行
Base * pb = & d;
pd = dynamic_cast<Derived*>(pb); // 安全的转换
if(pd == NULL)
cout << "unsafe dynamic_cast2" << endl; // 不会执行
return 0;
}