C++中隐式类型转换学习笔记
1operator隐式类型转换
1.1std::ref源码中reference_wrapper隐式类型转换
在std::ref的实现中有如下一段代码:
templateclassreference_wrapper :public_Reference_wrapper_base ::type> { _Tp*_M_data; public: typedef_Tptype; reference_wrapper(_Tp&__indata)noexcept :_M_data(std::__addressof(__indata)) {} reference_wrapper(_Tp&&)=delete; reference_wrapper(constreference_wrapper&)=default; reference_wrapper& operator=(constreference_wrapper&)=default; //operator的隐式类型转换 operator_Tp&()constnoexcept {returnthis->get();} _Tp& get()constnoexcept {return*_M_data;} template typenameresult_of<_Tp&(_Args&&...)>::type operator()(_Args&&...__args)const { return__invoke(get(),std::forward<_Args>(__args)...); } };
注意看operator操作符重载:
operator_Tp&()constnoexcept {returnthis->get();}
就是用于类型转换。
1.2简单的例子-实现一个class转为int的示例
#include/* * *c++operator的隐式类型转换 *参见std::ref的实现 */ voidf(inta) { std::cout<<"a="< 当然除了通过operator实现隐式类型转换,c++中还可以通过构造函数实现。
2构造函数实现隐式类型转换
在c++primer一书中提到
可以用单个实参来调用的构造函数定义了从形参类型到该类类型的一个转换
看如下示例:
#include/* * *c++构造的隐式类型转换 *参见std::ref的实现 */ classB{ public: B(inta):num(a){} ~B(){} intnum; }; classA{ public: A(inta):num(a){} A(Bb):num(b.num){} ~A(){} intfun(Aa) { std::cout< 特别需要注意的是单个实参,构造函数才会有隐式转换,一个条件不满足都是不行。
3使用explicit关键字避免构造函数隐式转换
有些时候我们并不希望发生隐式转换,不期望的隐式转换可能出现意外的结果,explicit关键词可以禁止之类隐式转换,将上述classA的构造函数改为如下
classA{ public: A(inta):num(a){} explicitA(Bb):num(b.num){} ~A(){} intfun(Aa) { std::cout<再次运行程序出现提示:
op2.cpp:Infunction‘intmain()':
op2.cpp:29:12:error:nomatchingfunctionforcallto‘A::fun(B&)'
a.fun(b);
^
op2.cpp:16:9:note:candidate:intA::fun(A)
intfun(Aa)
^~~
op2.cpp:16:9:note:noknownconversionforargument1from‘B'to‘A'这个时候调用方式修改更改为:
intmain() { Bb(1); Aa(2); a.fun(A(b)); return0; }只能感叹C++语言的博大精深,这篇文章还只是对隐式转换的入门级总结。
参考:
《C++Primer》隐式类类型转换学习整理
以上就是C++中隐式类型转换学习笔记的详细内容,更多关于C++中隐式类型转换的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。