Reputation: 129
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
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
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
Reputation: 1852
Both possibilities are possible.
http://en.cppreference.com/w/cpp/language/operators http://en.cppreference.com/w/cpp/language/operator_assignment (see the table)
Upvotes: 1