Operator Overloading is a concept that uses only in C++. A simple way to say about Operator Overloading is doing or setting to do arithmetic operations( Addition, Subtraction, Multiplication, Division, etc.....) to Objects.
If it is a normal variable it is easy to do this operations.( Eg: A = B + C
which A,B and C are integers). What happens if A, B and C were Objects. If they are objects they also individually have some variables. So we cant use normal arithmetic to them.
Eg:
class test
{
int a,b,c;
public:
void print();
};
Assume that A,B and C are objects of class test. What will happens if we use this kind of operation A = B + C. Program doesn't know what to do in the object. Shall B.a + C.a must assign to A.a or B.a + B.b + B.c must assign to A.a?? Program doesn't know. So we have to tell the program what to do if this happens. That is what called Operator Overloading. This is just a simple definition.
The following program is mostly about Operator Overloading. But it contains about friend functions, constructors, destructors and some about function overloading.
//Operator Overloading
#include
#include
using namespace std;
class dimension
{
int x, y, z;
public:
// Constructos And Destructors
dimension();
dimension( int );
~dimension();
// Member Functions
void display() // Inline
{
cout << x << " " << y << " " << z;
}
void input();
// Operator Overloading
friend dimension operator - ( dimension );
friend dimension operator - ( dimension, dimension );
dimension operator + ( dimension );
};
dimension :: dimension()
{
x = 0;
y = 0;
z = 0;
}
dimension :: dimension( int a )
{
x = a;
y = 0;
z = 0;
}
dimension :: ~dimension()
{
cout << " ";
}
void dimension :: input()
{
cout << "Enter Values for x, y and z:";
cin >> x >> y >> z;
}
dimension operator - ( dimension a )
{
dimension temp;
temp.x = -a.x;
temp.y = -a.y;
temp.z = -a.z;
return temp;
}
dimension operator - ( dimension a, dimension b )
{
dimension temp;
temp.x = ( a.x - b.x );
temp.y = ( a.y - b.y );
temp.z = ( a.z - b.z );
return temp;
}
dimension dimension :: operator + ( dimension a )
{
dimension temp;
temp.x = ( x + a.x );
temp.y = ( y + a.y );
temp.z = ( z + a.z );
return temp;
}
void main()
{
dimension A, B, C, D, E;
cout << "Enter Values For A and B\n";
A.input();
B.input();
C = -A;
C.display();
D = A + B;
D.display();
E = B - A;
E.display();
getch();
}
0 comments:
Post a Comment