Thursday, June 25, 2009

The symbolic operators (+ - * / ...) can be defined for new data types



NOTE : -
THIS CONTENT IS NOT ORIGINAL

14. The symbolic operators (+ - * / ...) can be defined for new data types

OPERATOR OVERLOADING can be used to redefine the basic symbolic operators for new kinds of parameters:


using namespace std;
#include

struct vector
{
double x;
double y;
};

vector operator * (double a, vector b)
{
vector r;

r.x = a * b.x;
r.y = a * b.y;

return r;
}

int main ()
{
vector k, m; // No need to type "struct vector"

k.x = 2; // To be able to write
k.y = -1; // k = vector (2, -1)
// see chapter 19.

m = 3.1415927 * k; // Magic!

cout << "(" << m.x << ", " << m.y << ")" << endl;

return 0;
}


Output
(6.28319, -3.14159)



Besides multiplication, 43 other basic C++ operators can be overloaded, including +=, ++, the array [], and so on...

The
<< operator, normally used for binary shifting of integers, can be overloaded to give output to a stream instead (e.g., cout <<). It is possible to overload the <<operator further for the output of new data types, like vectors:


using namespace std;
#include

struct vector
{
double x;
double y;
};

ostream& operator << (ostream& o, vector a)
{
o << "(" << a.x << ", " << a.y << ")";
return o;
}

int main ()
{
vector a;

a.x = 35;
a.y = 23;

cout << a << endl; // Displays (35, 23)

return 0;
}


Output
(35, 23)



BIBILOGRAPHY / REFERENCE : - http://www.4p8.com/eric.brasseur/cppcen.html

No comments:

3G S

JAIL BREAK

iPHONE

BILL GATES

StEvE JoBs

steve jobs

STEVE JOBS

Steve Jobs

Love Country

SD

Burroughs

Lift

Joseph Johnson

Apple Rainbow

Apple Blue

Apple Laser Printer