[C++] 强制类型转换(dynamic_cast和dynamic_Pointer_cast)

简介: [C++] 强制类型转换(dynamic_cast和dynamic_Pointer_cast)

1、指引或者引用的向上转换,向下转换

例如基类Father ,Son继承Father,派生类Son.。Father—>Son则为向下转换,Son—>Father则为向上转换。向上转换为隐士转换,向下转换需要dynamic_cast或者c的转换方式。

向上转换:

struct Father
{
  //基类Father
};
struct Son:Father
{
  //基类Father的派生类B
};
//1.普通指针转换
Son *son = new Son;
//派生类Son向上转换为基类Father
Father *father = son;
//2.智能指针转换
std::shared_ptr<Father> father(new Son(son));

此时son就是向上转换。无需显式转换既可以编译通过。

2、dynamic_cast

一般用于有继承关系的类之间的向下转换。

3、dynamic_pointer_cast

当指针是智能指针时候,向下转换,用dynamic_Cast 则编译不能通过,此时需要使用dynamic_pointer_cast。

向下转换(含智能指针):

struct Father
{
  //基类Father
};
struct Son:Father
{
  //基类Father的派生类B
};
std::shared_ptr<Father> father;
std::shared_ptr<Son> son = std::dynamic_pointer_cast<Son>(father);

戳戳小手帮忙点个免费的赞和关注吧,嘿嘿。
目录
相关文章
|
1月前
|
安全 编译器 程序员
【C++入门到精通】C++类型的转换 | static_cast | reinterpret_cast | const_cast | dynamic_cast [ C++入门 ]
【C++入门到精通】C++类型的转换 | static_cast | reinterpret_cast | const_cast | dynamic_cast [ C++入门 ]
21 0
|
1月前
|
存储 安全 编译器
【C++ 多态 】深入理解C++的运行时类型信息(RTTI):dynamic_cast和typeid的应用与原理
【C++ 多态 】深入理解C++的运行时类型信息(RTTI):dynamic_cast和typeid的应用与原理
120 1
|
1月前
|
人工智能 安全 机器人
【C++】dynamic_cast基本用法(详细讲解)
【C++】dynamic_cast基本用法(详细讲解)
|
1月前
|
安全 编译器 C语言
【C++ 类型转换关键字 *_cast 】理解const_cast、reinterpret_cast、dynamic_cast和static_cast的用法
【C++ 类型转换关键字 *_cast 】理解const_cast、reinterpret_cast、dynamic_cast和static_cast的用法
34 0
|
1月前
|
编译器 C++
我刚才用了dynamic_cast 你给我普及一下C++ 中这几种类型转换吧
我刚才用了dynamic_cast 你给我普及一下C++ 中这几种类型转换吧
31 0
|
1月前
|
安全 编译器 程序员
[C++ 从入门到精通] 6.static_cast、dynamic_cast等显示类型转换
[C++ 从入门到精通] 6.static_cast、dynamic_cast等显示类型转换
40 0
|
安全 C++
C++11之强制类型转换(static_cast,const_cast,dynamic_cast,reinterpret_cast)
C++11之强制类型转换(static_cast,const_cast,dynamic_cast,reinterpret_cast)
94 0
|
3天前
|
C++
C++一分钟之-类与对象初步
【6月更文挑战第20天】C++的类是对象的蓝图,封装数据和操作。对象是类的实例。关注访问权限、构造析构函数的使用,以及内存管理(深拷贝VS浅拷贝)。示例展示了如何创建和使用`Point`类对象。通过实践和理解原理,掌握面向对象编程基础。
30 2
C++一分钟之-类与对象初步