2011年2月13日星期日

一個用來展示 C++ casting 的簡單程序

  1 #include <iostream>
2 using std::cout;
3 using std::endl;
4
5 class base {
6 public:
7 int x;
8
9 base() { x = 0; };
10 virtual ~base() {};
11 };
12
13 class child_a : public base {
14 public:
15 int a;
16
17 child_a() { a = 0; };
18 };
19
20 class child_b : public base {
21 public:
22 int b;
23
24 child_b() { b = 0; };
25 };
26
27 void class_check_a(base *p) {
28 child_a *ptr_a;
29
30 // check actual object type
31 ptr_a = dynamic_cast<child_a*>(p);
32
33 if(ptr_a) {
34 cout << "It is a child a" << endl;
35 } else {
36 cout << "It is not a child a" << endl;
37 }
38 }
39
40 void class_check_b(base *p) {
41 child_b *ptr_b;
42
43 // check actual object type
44 ptr_b = dynamic_cast<child_b*>(p);
45
46 if(ptr_b) {
47 cout << "It is a child b" << endl;
48 } else {
49 cout << "It is not a child b" << endl;
50 }
51 }
52
53 int main(int argc, char* argv[]) {
54 // RTTI example
55 child_a a;
56 child_b b;
57
58 class_check_a(&a);
59 class_check_a(&b);
60
61 class_check_b(&a);
62 class_check_b(&b);
63
64 // reinterpret_cast and static_cast
65 int num_base = 10;
66 double num_1 = 0, num_2 = 0;
67
68 num_1 = static_cast<double>(num_base);
69 //num_2 = reinterpret_cast<double&>(num_base);
70
71 cout << "num_base = " << num_base << endl;
72 cout << "num_1 = " << num_1 << endl;
73 cout << "num_2 = " << num_2 << endl;
74
75 // const_cast
76 const child_a ca;
77 child_a *ptr_ma;
78
79 cout << "ca.a = " << ca.a << endl;
80
81 // enable it to generate error message
82 // becasue ca is a constant class
83 //ca.a = 10;
84
85 // from const to non-const
86 ptr_ma = const_cast<child_a*>(&ca);
87 ptr_ma->a = 10;
88
89 cout << "ca.a = " << ca.a << endl;
90
91 return 0;
92 }
93
94

沒有留言: