ここでの他の回答で問題は解決しますが、これを行うときに使用するパターンは次のとおりです。
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;
}
このアプローチの主な利点の 1 つは、必要なコード全体の量を削減して、関数を相互に実装できることです。
アップデート:
パフォーマンスの問題を寄せ付けないようにするために、おそらく非メンバー operator+ を次のようなインライン関数として定義します。
inline Num operator+(Num lhs, Num const & rhs)
{
lhs+=rhs;
return lhs;
}
int
メンバー操作も (クラス本体で宣言されているため) インラインであるため、すべてのコードは 2 つの生のオブジェクトを追加するコストに非常に近いはずです。
最後に、jalf が指摘したように、一般的に暗黙の変換を許可することの結果を考慮する必要があります。上記の例では、整数型から 'Num' に変換することが賢明であると想定しています。