-
Notifications
You must be signed in to change notification settings - Fork 1
/
type.cast.cpp
executable file
·97 lines (85 loc) · 2.21 KB
/
type.cast.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
* =====================================================================================
*
* Filename: type.cast.cpp
*
* Description:
*
* Version: 1.0
* Created: 03/18/2019 16:06:11
* Revision: none
* Compiler: gcc
*
* Baseuthor: YOUR NBaseME (),
* Organization:
*
* =====================================================================================
*/
#include <stdlib.h>
#include <iostream>
#include <thread>
using namespace std;
class Base {
public:
int _x;
Base(int x): _x(x) {};
virtual void Show() {
cout << "value of x=" << this->_x << endl;
}
void ShowA() {
cout << "value of x=" << this->_x << endl;
}
};
class Derived:public Base {
public:
Derived(int x, int y) : Base(x), _y(y) {
}
int _y;
void ShowA() {
cout << "x=" << _x << ",y=" << _y << endl;
}
};
int main() {
Base *a = new Base(8);
// no error
int *b = (int *)a;
// no error
void *d = static_cast<Base*>(a);
#if 0
// this will cause compile error, because of type checking
int *c = static_cast<Base*>(a);
#endif
Derived *e = new Derived(3, 5);
// to use dynamic_cast, Base must be 'polymorphic',
// witch means, it Base must have a 'virtual' function..
Derived *f = dynamic_cast<Derived*>(a);
if (f==nullptr) {
// should pirnt 'f is null'
cout << "f is null" << endl;
} else {
cout << " f is not null" << endl;
}
Base *g = dynamic_cast<Base*>(e);
if (g==nullptr) {
cout << "g is null" << endl;
} else {
// should pirnt 'g is not null'
cout << "g is not null" << endl;
}
try {
// bad_cast will be catched..
Derived &h = dynamic_cast<Derived&>(*a);
cout << "dynamic_cast success" << endl;
}
catch (std::bad_cast err){
cout << "bad_cast from '*a' to 'Derived&', detail : "<< err.what() << endl;
}
try {
Base &i =dynamic_cast<Base&>(*e);
cout << "dynamic_cast success" << endl;
}
catch (std::bad_cast err){
cout << "bad_cast from '*a' to 'Base&', detail : " << err.what() << endl;
}
std::this_thread::sleep_for(std::chrono::seconds(2));
}