Types of Operator Overloading in C++
1.overloading unary operator
2.overloading binary operator
Fig:Types of Operator Overloading in C++
1.Overloading unary operator
In
unary operator function, no arguments should be passed. It works only with one
class objects. It is a overloading of an operator operating on a single
operand.
Program:
#include
<iostream>
#include<conio.h>
class base
{
public:
int a,b;
base(int f, int i)
{
this->a = f;
this->b = i;
}
void operator-()
{
a--;
b--;
cout << "\n
a and b value: " << a << "'" << b;
}
};
void main()
{
Base d1(8, 9);
-d1;
getch();
}
Output:
a and b value 7’8
2.Overloading binary operator
In
binary operator overloading function, there should be one argument to be
passed. It is overloading of an operator operating on two operands.
Program:
#include
<iostream>
class Distance {
public:
int feet, inch;
Distance()
{
this->feet = 0;
this->inch = 0;
}
Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}
Distance
operator+(Distance& d2) // Call by reference
{
Distance d3;
d3.feet = this->feet
+ d2.feet;
d3.inch = this->inch
+ d2.inch;
return d3;
}
};
int main()
{
Distance d1(8, 9);
Distance d2(10, 2);
Distance d3;
d3 = d1 + d2;
cout <<
"\nTotal Feet & Inches: " << d3.feet << "'"
<< d3.inch;
getch();
}
No comments:
Post a Comment