0%

dynamic_cast转换

  1. 定义:沿着继承层次结构向上、向下和横向安全地将指针和引用转换为类。
  2. 表达式:
1
dynamic_cast < new-type > ( expression )

new-type必须是类的指针、引用或者void*

如果type-id是类指针类型,那么expression也必须是一个指针,如果type-id是一个引用,那么expression也必须是一个引用。

此处引用:[dynamic_cast彻底明白了~][https://blog.csdn.net/hongkangwl/article/details/21161713]

  1. 如果强制转换成功,dynamic_cast将返回一个类型为新型的值。如果转换失败,并且new-type是指针类型,那么它将返回该类型的空指针。如果转换失败,并且new-type是引用类型,则抛出一个与std::bad_cast类型的处理程序匹配的异常。
  2. 注意:
    • dynamic_cast在将父类cast到子类时,父类必须要有虚函数,否则编译器会报错。
    • dynamic_cast主要用于类层次间的上行转换和下行转换,还可以用于类之间的交叉转换。
    • 在类层次间进行上行转换时,dynamic_cast和static_cast的效果是一样的;
    • 在进行下行转换时,dynamic_cast具有类型检查的功能,比static_cast更安全。

转载原文链接:[dynamic_cast用法总结][https://blog.csdn.net/weixin_44212574/article/details/89043854]

  1. 例子
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
#include <iostream>
#include <assert.h>

using namespace std;

// 我是父类
class Tfather
{
public:
virtual void f() { cout << "father's f()" << endl; }
};

// 我是子类
class Tson : public Tfather
{
public:
void f() { cout << "son's f()" << endl; }

int data; // 我是子类独有成员
};

int main()
{
Tfather father;
Tson son;
son.data = 123;

Tfather *pf;
Tson *ps;

/* 上行转换:没有问题,多态有效 */
ps = &son;
pf = dynamic_cast<Tfather *>(ps);
pf->f();

/* 下行转换(pf实际指向子类对象):没有问题 */
pf = &son;
ps = dynamic_cast<Tson *>(pf);
ps->f();
cout << ps->data << endl; // 访问子类独有成员有效

/* 下行转换(pf实际指向父类对象):含有不安全操作,dynamic_cast发挥作用返回NULL */
pf = &father;
ps = dynamic_cast<Tson *>(pf);
assert(ps != NULL); // 违背断言,阻止以下不安全操作
ps->f();
cout << ps->data << endl; // 不安全操作,对象实例根本没有data成员

system("pause");
}