当前位置:网站首页>C++编程经验(6):使用C++风格的类型转换
C++编程经验(6):使用C++风格的类型转换
2021-08-07 23:42:49 【看,未来】
为什么推荐使用C++风格类型转换?
不是说别的风格的类型转换机制不好,但是写C++代码的话,既然人家有,那就慢慢的适应嘛,入乡随俗。
我们以前写类型转换一般是这样的:(type) expression,而C++引进了四个类型转换的操作符:
static_cast const_cast dynamic_cast reinterpret_cast
- 1.
- 2.
- 3.
- 4.
以前那样写,现在只不过改成这样写:static_cast(expression)
举个例子哈:
假设你想把一个 int 转换成 double,以便让包含 int 类型变量的表达式产生出浮点数值的结果。
如果用 C 风格的类型转换,你能这样写:
int a; ... double b = (double)a;
- 1.
- 2.
- 3.
如果用上述新的类型转换方法,你应该这样写:
double result = static_cast<double>(a);
- 1.
如何驾驭C++风格的类型转换?
static_cast 就不多说了吧,前面提到了,功能呢,跟C风格的类型转换功能大体上是一样的。
不过呢,它也有功能上限制。例如,你不能用 static_cast 象用 C 风格的类型转换一样把 struct 转换成 int 类型或者把 double 类型转换成指针类型,另外,static_cast 不能从表达式中去除 const 属性,因为这是别的类型转换符(const_cast)的功能。
const_cast 用于且仅用于类型转换掉表达式的 const 或 volatileness 属性。
class father { ... }; class son: public father { ... }; void update(son* psw); son sw; // sw 是一个非 const 对象。 const son& csw = sw; // csw 是 sw 的一个引用,它是一个 const 对象 update(&csw); // 错误!不能传递一个 const son* 变量给一个处理 son*类型变量的函数 update(const_cast<son*>(&csw)); // 正确,csw 的 const 被显示地转换掉 update((son*)&csw); // 同上,但用了一个更难识别的 C 风格的类型转换 father *pw = new son; update(pw); // 错误!pw 的类型是 father*,但是 update 函数处理的是 son*类型 update(const_cast<son*>(pw));// 错误!const_cast 仅能被用在影响 constness or volatileness 的地方上。, // 不能用在向继承子类进行类型转换。
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
dynamic_cast,它被用于安全地沿着类的继承关系向下进行类型转换。这就是说,你能用 dynamic_cast 把指向基类的指针或引用转换成指向其派生类或其兄弟类的指针或引用,而且你能知道转换是否成功。失败的转换将返回空指针(当对指针进行类型转换时)或者抛出异常(当对引用进行类型转换时):
father* pw; ... update(dynamic_cast<son*>(pw)); // 正确,传递给 update 函数一个指针是指向变量类型为 son的 pw 的指针 void updateViaRef(son& rsw); updateViaRef(dynamic_cast<son&>(*pw)); //正确。 传递给 updateViaRef 函数 SpecialWidget pw 指针,如果 pw
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
这四个类型转换符中的后一个是 reinterpret_cast。emmm,好像这个转换符不是很受待见。
使用这个操作符的类型转换,其的转换结果几乎都是执行期定义。 因此,使用reinterpret_casts 的代码很难移植。
reinterpret_casts 的普通的用途就是在函数指针类型之间进行转换。
转换函数指针的代码是不可移植的(C++不保证所有的函数指针都被用一样的方法表示),在一些情况下这样的转换会产生不正确的结果,所以你应该避免转换函数指针类型,除非万不得已。
版权声明
本文为[看,未来]所创,转载请带上原文链接,感谢
https://blog.51cto.com/u_15197573/3310088
边栏推荐
- Fourth in the world! Wang Sicong installed a server "readily". Netizen: trench is inhuman
- [Tencent classroom] creator zero foundation immortal practice is online!
- 跟着华为,学数字化转型(3):模式创新
- 记一次接口慢查排查
- Follow Huawei and learn digital transformation (3): mode innovation
- Record an interface slow check and troubleshooting
- @Autowired的这些骚操作,你都知道吗?
- ss -h命令
- @Do you know all these operations of Autowired?
- 使用Yolo v5进行目标检测
猜你喜欢
-
Yazid的新生舞会(线段树)
-
当creator遇上protobufjs|孕育
-
Identify and stop the process that‘s listening on port 8080 or configure this application to listen
-
为什么要推荐大家学习字节码?
-
揭秘!价值百万的像素填色解决方案,想开发绘本应用的有福了!
-
[PyTroch系列-11]:PyTorch基础 - 张量Tensor元素的排序
-
[PyTroch系列-12]:PyTorch基础 - 张量Tensor线性运算(点乘、叉乘)
-
【环境篇】第 3 节 • Navicat 环境安装
-
预训练语言模型的前世今生 - 从Word Embedding到BERT
-
讲道理,只要你是一个爱折腾的程序员,毕业找工作真的不需要再花钱培训!
随机推荐
- 华南理工 | 基于生成式的低比特无数据量化
- 微信小程序授权位置和用户信息权限(防止用户禁止后无法使用位置信息)
- 一行代码快速实现今日头条 网易新闻焦点图自动循环轮播效果
- 因果涌现:数学理论揭示整体怎样大于部分之和
- 年收入百万美元AI科学家的烦恼
- API《为什么奥运会以五色环为标志?》数据源接口
- 用一张草图创建GAN模型,新手也能玩转,朱俊彦团队新研究入选ICCV 2021
- UIUC | 用于语言模型的课程学习
- SS - H command
- Target detection using Yolo V5
- Yazid's freshman ball (thread tree)
- When creator meets protobufjs 𞓜
- 我敢肯定!你还没用过一款代码神器,只属于Creator的用户!
- 小程序页面跳转&&文章详情页的实现&&markdown格式转化为wxml显示在小程序页面里
- 49个项目管理过程ITTO整理(详细)
- 49个项目管理过程ITTO整理(详细-文字版)
- 只是想虐下春丽,一不小心撸了台游戏机...
- Cocos论坛九问九答
- Identify and stop the process that‘s listening on port 8080 or configure this application to listen
- 超详细的I/O多路复用概念、常用I/O模型、系统调用等介绍
- Why recommend learning bytecode?
- SAP Commerce Cloud UI 的用户会话管理
- 以太坊 交易 data字段 内容是什么
- SAP CRM Fiori 应用 My Note 里创建 Note 失败的一个原因分析
- 当creator遇上protobufjs|pbkiller填坑历险记
- Uncover the secret! Millions of pixel color filling solutions. Blessed are those who want to develop picture book applications!
- [pytroch series - 11]: pytorch basis - ordering of tensor tensor elements
- [pytroch series - 12]: pytorch basis tensor tensor linear operation (point multiplication, cross multiplication)
- [environment] section 3 • Navicat environment installation
- The past and present life of pre training language model - from word embedding to Bert
- Make sense, as long as you are a tossing programmer, you really don't need to spend money on training to find a job after graduation!
- South China Technology | low bit no data quantization based on generative
- Wechat applet authorizes location and user information permissions (to prevent users from being unable to use location information after prohibition)
- One line of code can quickly realize the automatic circular rotation effect of today's headlines and Netease News focus map
- Causal emergence: mathematical theory reveals how the whole is greater than the sum of parts
- The troubles of AI scientists with an annual income of millions of dollars
- API "why is the Olympic Games marked by five color rings?" Data source interface
- Create a GaN model with a sketch, which can be played by novices. The new research of Zhu Junyan's team was selected into iccv 2021
- UIUC | course learning for language model
- I'm sure! You haven't used a code artifact yet. It only belongs to creator users!