Reputation: 327
For educative purposes, I wish to overload and use the += operator in cascade.
class a {
public:
a();
a& operator+= (float f);
private:
float aa;
}
a() {
aa = 0;
}
a& operator+= (float f) {
aa += f;
return *this;
}
a b;
b += 1.0; // Works.
b += 1.0 += 1.0; // Error : Expression must be a modifiable lvalue.
I don't understand why the above doesn't work (aside of the possible syntax mistakes -- didn't try to compile this sample code). Returning *this in the overloaded operator+= method, I would expect the second += 1.0 to be called on the b object, no?
Thanks.
Upvotes: 14
Views: 2680
Reputation: 7068
Just to add to the fine answers you got. You might be interested in converting constructors and/or conversion operators. For instance:
class a {
public:
a();
a(float f);
a& operator+= (float f);
operator float() const;
private:
float aa;
};
a::a() {
aa = 0;
}
a::a(float f) {
aa = f;
}
a& a::operator+= (float f) {
aa += f;
return *this;
}
a::operator float() const {
return aa;
}
int main()
{
a b = 1.0;
b += 1.0; // Works.
b += (a)1.0 += 1.0; // Works.
}
or maybe better without conversion operator, but with operator+=(const a&);
class a {
public:
a();
a(float f);
a& operator+= (float f);
a& operator+= (const a & x);
private:
float aa;
};
a::a() {
aa = 0;
}
a::a(float f) {
aa = f;
}
a& a::operator+= (float f) {
aa += f;
return *this;
}
a& a::operator+= (const a & x) {
aa += x.aa;
return *this;
}
int main()
{
a b = 1.0;
b += 1.0; // Works.
b += (a)1.0 += 1.0; // Works.
}
Upvotes: 0
Reputation: 70546
Please note that in order to have a class a
with the least amount of surprise for its users, it's probably best to also define a member function
a& operator+=(a const&);
as well as non-member functions
a operator+(a const&, a const&);
a operator+(a const&, float);
a operator+(float, a const&);
that are each defined in terms of one of the member operator+=
overloads. Then you can write
a1 += b1 + c1;
where a1
is of type a
the variables b1
, c1
can both be either float
or a
. See this question from the c++-faq for more details.
Upvotes: 1
Reputation: 361662
b += 1.0 += 1.0;
The associativity for +=
is right-to-left. So the above is interpreted as:
(b += (1.0 += 1.0));
Does that make sense? NO.
In order to make it work, you need to write it as:
(b += 1.0) += 1.0;
Hope that helps.
Upvotes: 26