|
Operator-Assignment Overloading
In this section, we will study overloading the Operator-Assignment operators. This group consists of those operators where
the operation and assignment take place in the same statement, such as: +=, -=, *=, /=, %=, <<=, >>=, |= etc.
We will study how to overload += and the same principles can be applied to the others. As before, we start by declaring
a member function:
class Complex {
private:
double real, imag;
public:
Complex() { real = imag = 0; }
....
Complex& operator+=(const Complex& num);
};
Complex& Complex::operator+=(const Complex& num) {
real += num.real;
imag += num.imag;
return *this;
}
int main(void) {
Complex num1(2, 3);
Complex num2(3, 5);
num1 += num2;
cout << "num1 is " << num1.GetReal() << " + "
<< num1.GetImag() << "i" << endl;
}
We can also implement the same thing using global functions. The code below implements += between two Complex class objects
and between a Complex and a double using global functions. It is assumed that SetReal() and SetImag() from the
Arithmetic with Globals page are implemented.
class Complex {
private:
double real, imag;
public:
Complex() { real = imag = 0; }
....
// Comment out -- Complex& operator+=(const Complex& num);
};
// Add two Complex class objects (Complex += Complex)
Complex& operator+=(Complex &lhs, const Complex& rhs) {
lhs.SetReal(lhs.GetReal() + rhs.GetReal());
lhs.SetImag(lhs.GetImag() + rhs.GetImag());
return lhs;
}
// Code for Complex += double
Complex& operator+=(Complex& lhs, const double& rhs) {
lhs.SetReal(lhs.GetReal() + rhs);
return lhs;
}
int main(void) {
Complex num1(2, 3);
Complex num2(3, 5);
num1 += num2;
cout << "num1 is " << num1.GetReal() << " + "
<< num1.GetImag() << "i" << endl;
double d = 24.34;
num1 += d;
cout << "num1 is " << num1.GetReal() << " + "
<< num1.GetImag() << "i" << endl;
}
The variables are named lhs and rhs to indicate on which side of the expression they are on (Left Hand Side or
Right Hand Side). As you can see, the code for implementing them as global functions is pretty easy as well. All we are doing
is taking the values from the right hand side variable and adding them to the left hand side variable. Finally, we return
a reference to the left hand side variable.
Exercises
1. Implement Complex += double as a member function instead of a global function.
2. Implement -= and *= functions. You can choose whether to implement as member functions or globals.
|
|