Template class : Write a template class and add two number. Test integer and double type value inside main.
- define Template
- define class
- variable should be Template type
- add two number
- test inside main
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
using namespace std; | |
template<class T> // template definition | |
class Add // class starts | |
{ | |
private: | |
T a;// variable which is type T | |
T b;// | |
public: | |
Add(T a,T b)// define value | |
{ | |
this ->a=a; | |
this ->b=b; | |
} | |
T sum()// function which return sum of type T | |
{ | |
return(a+b); | |
} | |
}; | |
int main() | |
{ | |
Add<int>a(1,2);// supply int type value | |
cout<<"Sum of integer number :"<<a.sum()<<endl; | |
Add <double>b(1.2,2.3);//supply double type value | |
cout<<"Sum of double number :"<<b.sum()<<endl; | |
return 0; | |
} |
Sum of integer number :3 Sum of double number :3.5
0 Comments
If you have any doubt and suggestion Please let me know