/*----------------------------------------------------- Script for AdSense -----------------------------------------------------*/ /* */ /* Footer ----------------------------------------------- */ #footer { clear: both; text-align: center; color: #333333; } #footer .widget { margin:.5em; padding-top: 20px; font-size: 85%; line-height: 1.5em; text-align: left; } /** Page structure tweaks for layout editor wireframe */ body#layout #header { width: 750px; } -->

Thursday, April 29, 2010

Operator Overloading

When an operator is overloaded, none of its original meaning is lost. It simply means that a new operation relative to a specific class is defined.
To overload an operator, you must define what that operation means relative to the class that it is applied to. To do this you create an operator function, which defines its action. The general form of a member operator function is


type classname::operator#(arg-list)
{

// operation defined relative to the class
}


This program overloads the + operators relative to the Complex class: from MSDN



// operator_overloading.cpp
// compile with: /EHsc
#include <iostream>

using namespace
std;
class
Complex
{

public
:
Complex( double r, double i ) : re(r), im(i) {}
Complex operator+( Complex &other );
void
Display( ) { cout << re << ", " << im << endl; }
private
:
double
re, im;
};


// Operator overloaded using a member function
Complex Complex::operator+( Complex &other )
{

return
Complex( re + other.re, im + other.im );
}


int
main()
{

Complex a = Complex( 1.2, 3.4 );
Complex b = Complex( 5.6, 7.8 );
Complex c = Complex( 0.0, 0.0 );

c = a + b;
c.Display();
}




friend Operator Functions:
It is possible for an operator function to be a friend of a class rather than a member. since friend functions are not members of a class, they do not have the implied argument this. Therefore, when a friend is used to overload an operator, both operands are passed when overloading binary operators and a single operand is passed when overloading unary operators.
The only operators that cannot use friend functions are =, ( ), [ ], and ->. The rest can use either member or friend functions to implement the specified operation relative to its class.
As friend overloaded function require two operand then we can do object + int addition or int + object using friend +operator overloading.

No comments: