I have a Java background and trying to learn C++. I have code like one shown below. I am trying to understand when should I overload the operator like this complex operator+(const complex& c2)
and when should I overload the operator like this complex operator+(complex a, complex b)
. I cannot have both the functions at the same time as the compiler complains about ambiguity so I have commented one out. Both functions (former is a method of the class) produce same result:
#include <iostream>
using namespace std;
//This class is in global scope
class complex {
private:
double re, im;
public:
complex(double r, double i): re {r}, im {i} {}
double real() const {
return re;
}
void real(double r) {
re = r;
}
double imag() const {
return im;
}
void imag(double i) {
im = i;
}
/*
complex operator+(const complex& c2) {
cout << "Single arg operator+\n";
complex c = complex(0, 0);
c.real(re + c2.real());
c.imag(im + c2.imag());
return c;
}
*/
complex& operator+=(const complex& c2) {
cout << "operator+=\n";
re += c2.real();
im += c2.imag();
return *this;
}
void print() {
cout << "Real: " << re << ", Imaginary: " << im << "\n";
}
};
//This function is in global scope
complex operator+(complex a, complex b) {
cout << "Double arg operator+\n";
return a += b;
}
int main() {
complex c = complex(2, 3);
complex c2 = complex(2, 3);
complex c3 = c + c2;
c.print();
c += c2;
c.print();
}