17

私は次のクラスを持っています:-

class myclass
{
    size_t st;

    myclass(size_t pst)
    {
        st=pst;
    }

    operator int()
    {
        return (int)st;
    }

    int operator+(int intojb)
    {
        return int(st) + intobj; 
    }

};

これは、次のように使用する限り正常に機能します:-

char* src="This is test string";
int i= myclass(strlen(src)) + 100;

しかし、私はこれを行うことができません:-

int i= 100+ myclass(strlen(src));

どうすればこれを達成できますか??

4

4 に答える 4

12

左側にプリミティブ int を許可するには、演算子を非メンバー関数として実装する必要があります。

int operator+( int lhs, const myclass& rhs ) {
    return lhs + (int)rhs;
}
于 2009-07-27T14:50:40.557 に答える
4

ここでの他の回答で問題は解決しますが、これを行うときに使用するパターンは次のとおりです。

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' に変換することが賢明であると想定しています。

于 2009-07-27T15:03:25.107 に答える