我有一个封装了一些算术的类,比如说定点计算。我喜欢重载算术运算符的想法,所以我写了以下内容:
class CFixed
{
CFixed( int );
CFixed( float );
};
CFixed operator* ( const CFixed& a, const CFixed& b )
{ ... }
这一切都有效。我可以写 3 * CFixed(0) 和 CFixed(3) * 10.0f。但现在我意识到,我可以更有效地使用整数操作数来实现 operator*。所以我超载它:
CFixed operator* ( const CFixed& a, int b )
{ ... }
CFixed operator* ( int a, const CFixed& b )
{ ... }
它仍然有效,但现在 CFixed(0) * 10.0f 调用重载版本,将 float 转换为 int (我希望它将 float 转换为 CFixed )。当然,我也可以重载浮点版本,但这对我来说似乎是代码的组合爆炸。是否有任何解决方法(或者我的课程设计错误)?如何告诉编译器仅使用整数调用重载版本的 operator*?