【M21】利用重载技术避免隐式类型转换

独自空忆成欢 提交于 2019-11-27 01:18:28

1、考虑UPint 的加法+,UPint a, b, result; 为了使result = a+10; result= 10+a; 都能通过编译,操作符重载如下:

  const UPint operator+(const UPint& lhs, const UPint& rhs);

  注意:不能使用成员操作符,否则result= 10+a;编译错误,因为隐式类型转换不能转换为this指针。

2、在result = 10+a;调用的过程中,10会隐式转换为UPint(条件是UPint单一形参构造方法不是explicit),这导致临时对象的产生,效率降低。

3、怎么解决这个问题呢?

  增加重载方法,如下:

  const UPint operator+(const UPint& lhs, const UPint& rhs);

  const UPint operator+(const UPint& lhs, int  rhs);

  const UPint operator+(int lhs, const UPint& rhs);

4、注意,千万不能写出 const UPint operator+(int lhs, int rhs) ,因为这将彻底改变int类型的加法意义,必将造成天下大乱。在C++,重载操作符的形参中至少要有一个自定义类型。也就是说,对于内置类型,禁止用户改变其操作符的含义。

5、重载技术避免了隐式类型转换,不再产生临时对象。但是增加了一系列重载的方法,这不见得是个好办法。需要在两种方式中进行取舍。

转载于:https://www.cnblogs.com/nzbbody/p/3567490.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!