Page 144 - DCAP404 _Object Oriented Programming
P. 144
Unit 7: Operator Overloading
In order to allow operations like Complex c = a+b, in above code we overload the “+” operator. Notes
The overloading syntax is quite simple, similar to function overloading, the keyword operator
must be followed by the operator we want to overload:
class Complex
{
public:
Complex(double re,double im)
:real(re),imag(im)
{};
Complex operator+(const Complex& other);
Complex operator=(const Complex& other);
private:
double real;
double imag;
};
Complex Complex::operator+(const Complex& other)
{
double result_real = real + other.real;
double result_imaginary = imag + other.imag;
return Complex( result_real, result_imaginary );
}
The assignment operator can be overloaded similarly. Notice that we did not have to call any
accessor functions in order to get the real and imaginary parts from the parameter other since
the overloaded operator is a member of the class and has full access to all private data.
Alternatively, we could have defined the addition operator globally and called a member to do
the actual work. In that case, we’d also have to make the method a friend of the class, or use an
accessor method to get at the private data:
friend Complex operator+(Complex);
Complex operator+(const Complex &num1, const Complex &num2)
{
double result_real = num1.real + num2.real;
double result_imaginary = num1.imag + num2.imag;
return Complex( result_real, result_imaginary );
}
LOVELY PROFESSIONAL UNIVERSITY 137