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

时间:2021-09-22 03:26:27

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