|
More on Assignment Operator Overloading
In the previous section, we saw how to overload the Assigment (=) operator between two objects
of the Complex class. However, what if we want to assign a simple double variable to a Complex
class variable. Recall that all real numbers are also complex numbers where the imaginary part
is 0. Thus, the real number 52.23 can be represented as the complex number 52.23 + 0i. Hence,
we must have a way to assign double variables to a Complex class.
As before, we start off by adding a definition in the class:
class Complex {
private:
double real, imag;
public:
Complex() { real = imag = 0; }
Complex(double r, double i) { real = r; imag = i; }
double GetReal(void) const { return real; }
double GetImag(void) const { return imag; }
Complex& operator=(const Complex& num);
Complex& operator=(const double& d);
};
The new operator tells the compiler that the Complex class can also be assigned to a variable
or value of type double and that it returns a reference to a Complex class. As before, we're
using the const keyword to assure the compiler that we're not going to tamper with the
passed in variable. The code will work without the const, but we're doing it to be polite.
Now we implement the method.
Complex& Complex::operator=(const double& d) {
real = d;
imag = 0;
return *this;
}
Then, we can test this new method out:
int main(void) {
Complex num1;
double x = 52.23;
num1 = x;
cout << "num1 is " << num1.GetReal() << " + "
<< num1.GetImag() << "i" << endl;
return 0;
}
Running this program provides the output:
num1 is 52.23 + 0i
This is exactly what we expected. As before, since the method returns *this, we can chain assignment
operations such as:
Complex a, b, c;
double d = 52.23;
a = b = c = d;
Some of you may already have noticed that the following code also works.
Complex x;
x = 52; // Assigning to an int
x = 52.23f; // Assigning to a float
This is because the C++ compiler knows how to promote an int or a float to a type
double and thus, it can use the operator that we overloaded for int and float as well.
Needless to say, you can also assign a variable of type char to the Complex class, since
char can be promoted to double as well. Of course, it is possible to write separate overloaded
functions that accept a reference to int, float, char etc. or even use templates to generate them, but
we will not dwell into those possibilities here.
Now, we will look at how to overload the arithmetic operators for Complex numbers. We will
start by redefining the addition operator (+).
|
|