Alex
Alex

Reputation: 129

operator overloading C++ +=

I have class Item and Item items and int q. I'm trying to make a function to overload+=. Would I need a friend function, or does it have to be member?

The statement in main program is

             items+=q;

in class Item header file:

   friend Item operator+=(const Item&, int&);

in class Item cpp file:

    Item operator+=(const Item& items, int& q)
    {
         items+=q;
         return items;
    }

And so compiler says no match for "+="

Upvotes: 2

Views: 154

Answers (3)

GreatAndPowerfulOz
GreatAndPowerfulOz

Reputation: 1775

change this:

Item operator+=(const Item& items, int& q)
    {
         items+=q;
         return items;
    }

to

Item operator+=(int q)
    {
         this->quanity += q;
         return *this;
    }

of course, this implies it's a member of the class...

Upvotes: 0

Zulukas
Zulukas

Reputation: 1290

A += operator may either return void like this:

class Point
{
private:
  int x;
  int y;
public:
  void operator += (const Point& operand)
  {
     this->x += operand.x;
     this->y += operand.y;
  }
};

or may return a reference:

class Point
{
private:
  int x;
  int y;
public:
  Point& operator += (const Point& operand)
  {
     this->x += operand.x;
     this->y += operand.y;

     return *this;
  }
};

The latter is the better way to do things as it allows chaining.

Upvotes: 1

Related Questions