Loading....
Coupon Accepted Successfully!

 

Class Templates With Overloaded Operators

The class template permits the overloaded operators and member functions to be declared. The syntax for creating the overloaded operator function is similar to the class template members and functions. The following program explains the overloaded operators with the template class:
 
17.13 Write a program to overload + operator for performing addition of two template based class objects.
#include<iostream.h>
#include<conio.h>
template<class T>
class num
{
private:
T number;
public:
num() {number=0;}
void input()
{
cout<<“\n Enter a number: ”;
cin>>number;
}
num operator +(num);
void show() {cout<<number;}
};
template<class T>
num <T> num <T> :: operator + (num <T> c)
{
num <T> tmp;
tmp.number=number+c.number;
return (tmp);
}
void main()
{
clrscr();
num <int> n1,n2,n3;
n1.input();
n2.input();
n3=n1+n2;
cout<<“\n\t n3=”;
n3.show();
}
OUTPUT
Enter a number : 8
Enter a number : 4
n3 = 12
  
Explanation: In the above program, class num is declared with a template variable number. The input() function is used to read the number through the keyboard. The operator +() function performs the addition of elements of two template objects.
 
In function main(), n1, n2, and n3 are three objects of the num class. The statement n3 = n1+n2 invokes the overloaded operator, and an addition of two objects is performed. The show() function displays the contents of the object.




Test Your Skills Now!
Take a Quiz now
Reviewer Name