Operator Overloading in C++ as int + obj

僤鯓⒐⒋嵵緔 提交于 2019-11-26 22:53:07

Implement the operator overloading outside of the class:

class Num
{
public:
    Num(int i)
    {
        this->i = i;
    }

    int i;
};

int operator+(int i, const Num& n)
{
    return i + n.i;
}

You have to implement the operator as a non-member function to allow a primitive int on the left hand side.

int operator+( int lhs, const myclass& rhs ) {
    return lhs + (int)rhs;
}

The other answers here will solve the problem, but the following is the pattern I use when I'm doing this:

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;
}

One of the key benefits of this approach is that your functions can be implemented in terms of each other reducing the amount of overall code you need.

UPDATE:

To keep performance concerns at bay, I would probably define the non member operator+ as an inline function something like:

inline Num operator+(Num lhs, Num const & rhs)
{
  lhs+=rhs;
  return lhs;
}

The member operations are also inline (as they're declared in the class body) and so in all the code should be very close to the cost of adding two raw int objects.

Finally, as pointed out by jalf, the consequences of allowing implicit conversions in general needs to be considered. The above example assumes that it's sensible to convert from an integral type to a 'Num'.

You need a global function operator+( int, myclass ) to do this:

int operator+( int intobj, myclass myobj )
{ return intobj + int(myobj); }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!