这里的其他答案将解决问题,但以下是我这样做时使用的模式:
class Num
{
public:
Num(int i) // Not explicit, allows implicit conversion to Num
: i_ (i)
{
}
Num (Num const & rhs)
: i_ (rhs.i_)
{
}
Num & operator+= (Num const & rhs) // Implement +=
{
i_ += rhs.i_;
return *this;
}
private:
int i_;
};
//
// Because of Num(int), any number on the LHS or RHS will implicitly
// convert to Num - so no need to have lots of overloads
Num operator+(Num const & lhs, Num const & rhs)
{
//
// Implement '+' using '+='
Num tmp (lhs);
tmp+=rhs;
return tmp;
}
这种方法的主要好处之一是您的功能可以相互实现,从而减少您需要的整体代码量。
更新:
为了避免性能问题,我可能会将非成员 operator+ 定义为内联函数,例如:
inline Num operator+(Num lhs, Num const & rhs)
{
lhs+=rhs;
return lhs;
}
成员操作也是内联的(因为它们是在类主体中声明的),因此在所有代码中应该非常接近添加两个原始int对象的成本。
最后,正如 jalf 所指出的,通常需要考虑允许隐式转换的后果。上面的示例假定从整数类型转换为“Num”是明智的。