That documentation is clearly for Java, which doesn't even have operator overloading.
No, operator+() and operator+=() are independent. If you want your class to support both, you need to define both overloads. If you only provide one overload and you try to use the one you didn't define, the compiler will simply reject the code, so it doesn't have any behavior. It's not even a valid program.
However, you can implement one in terms of the other:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class A{
A operator+(const A &) const;
const A &operator+=(const A &a){
return *this = *this + a;
}
};
class B{
const B &operator+=(const B &b);
B operator+(const B &b) const{
B ret = *this;
ret += b;
return ret;
}
};
very interesting. I think the codes using += passed compilers of both MS VS11 and Gcc 4.8.*, even though I only implemented +. Somehow, it worked as if I implemented += in LINUX, though I think it could be unexpected behaviors.
#include <iostream>
//#define DEFINEME
class A{
int a;
public:
A(int a): a(a){}
A operator+(const A &a) const{
return A(this->a + a.a);
}
int get_a() const{
returnthis->a;
}
#ifdef DEFINEME
const A &operator+=(const A &a){
this->a += a.a;
return *this;
}
#endif
};
int main(){
A a = 42;
A b = 24;
a += b;
std::cout << a.get_a() << std::endl;
return 0;
}