条款21:利用重载技术(overload)避免隐式型别转换(implicit type conversions)
class Rational
{
……
const Rational operator+(const Rational& lhs, const Rational rhs);
……
}
如果我们这么写:
Rational a(10);
Rational b(10,11);
Rational c = a + b;
这样当然是最理想的结果了,没有什么额外的成本,但事实往往并非如此,例如,Rational c = a + 10; C++当然很乐意将10转化成Rational对象,然而这意味的是成本的增加。所以,我们可以使用重载技术。
const Rational operator+(const Rational& lhs, const Rational& rhs);
const Rational operator+(int lhs, const Rational& rhs);
const Rational operator+(const Rational& lhs, int rhs);
当然我们做不到const Rational operator+(int lhs, int rhs);这违反了重载的规则。重载函数的弊端是容易混淆,增加了二义性出现的几率,所以如何权衡还需要看实际的情况。
本文探讨了在C++中通过重载运算符来避免隐式类型转换的方法,以此减少不必要的运行成本。文章提供了具体的代码示例,展示了如何为自定义类实现不同类型间的加法操作。
1051

被折叠的 条评论
为什么被折叠?



