类与对象R-2-1-2强制

禁止使用 reinterpret_cast 对虚基类向下转型

使用 reinterpret_cast 对虚基类向下转型
test.cpp
1class Shape
2{
3public:
4 virtual ~Shape();
5};
6
7class Rect : public virtual Shape
8{
9public:
10 ~Rect() override;
11};
12
13void foo()
14{
15 Shape *s = new Rect;
16 Rect *r1 = reinterpret_cast<Rect*>(s);
禁止使用 reinterpret_cast 对虚基类向下转型 [gjb8114-r-2-1-2]
17 Rect &r2 = reinterpret_cast<Rect&>(*s);
禁止使用 reinterpret_cast 对虚基类向下转型 [gjb8114-r-2-1-2]
18 Shape &rs = *s;
19 Rect &r3 = reinterpret_cast<Rect&>(rs);
禁止使用 reinterpret_cast 对虚基类向下转型 [gjb8114-r-2-1-2]
20}
使用 dynamic_cast 对虚基类向下转型
test.cpp
1class Shape
2{
3public:
4 virtual ~Shape();
5};
6
7class Rect : public virtual Shape
8{
9public:
10 ~Rect() override;
11};
12
13void foo()
14{
15 Rect r;
16 Shape *s = &r;
17 Rect *pr = dynamic_cast<Rect*>(s);
18 Rect &rr = dynamic_cast<Rect&>(*s);
19}