您的位置:首页 > 编程语言 > C语言/C++

More Effective C++之21

2006-06-16 09:22 267 查看
条款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);这违反了重载的规则。重载函数的弊端是容易混淆,增加了二义性出现的几率,所以如何权衡还需要看实际的情况。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: