C++_day9am

dynamic_cast

static_cast

reinterpret_cast

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class A{
 6 public:
 7     //动态类型转换只能用于多态继承
 8     virtual void foo(void){}
 9 };
10 
11 class B: public A{};
12 class C: public B{};
13 class D{};
14 
15 int main(void)
16 {
17     B b;
18     A* pa = &b; //B is a A --皆然性
19     cout << "pa= " << pa << endl;
20     cout << "动态类型装换" << endl;
21     //pa实际指向B类对象,转换成功
22     B* pb = dynamic_cast<B*> (pa);
23     cout << "pb= " << pb << endl;
24     //pa没有指向C类对象,转换失败,安全
25     C* pc = dynamic_cast<C*> (pa);
26     cout << "pc= " << pc << endl;
27     try{
28         A& ra = b;
29         C& rc = dynamic_cast<C&> (ra);
30     }
31     catch(exception& ex){
32         cout << ex.what() << endl;
33     }
34     //pa没有指向D类对象,转换失败,安全
35     D* pd = dynamic_cast<D*> (pa);
36     cout << "pd= " << pd << endl;
37     cout << "静态类型转换"  << endl;
38     //B是A的子类,转换成功
39     pb = static_cast<B*> (pa);
40     cout << "pb= " << pb << endl;
41     //C是A的孙子类,转换成功,危险
42     pc = static_cast<C*> (pa);
43     cout << "pc= " << pc << endl;
44     //D和A没有继承关系,转换失败,安全
45     //pd = static_cast<D*> (pa);
46     //cout << "pd= " << pd << endl;
47     cout << "重解释类型转换" << endl;
48     //编译期、运行期均不做检查,永远成功,最危险
49     pb = reinterpret_cast<B*> (pa);
50     cout << "pb= " << pb << endl;
51     pc = reinterpret_cast<C*> (pa);
52     cout << "pc= " << pc << endl;
53     pd = reinterpret_cast<D*> (pa);
54     cout << "pd= " << pd << endl;
55         
56     return 0;
57 }

猜你喜欢

转载自www.cnblogs.com/lican0319/p/10789069.html
am