| e.g.
#include<iostream> using namespace std; void Print(int A[], const int n)
int main()
Print(a,5);
system("pause"); Solution?
|
e.g.
int main()
Print(a,5);
}
|
class template
Similar to function template. No specific
type given for array element type.
The actual type is given during
the declaration of objects.
| Declaration 1.
class CL { .... .... int A[10]; };
|
Declaration 2.
CL<int> OBJ1; // A in OBJ1 is an array of 10 int.
|
Example:
#include<iostream> #include<string> using namespace std;template<class T> class Sample { private: T num[5]; public: Sample (T aNum[5]); //constructor T getSum(); };template<class T> Sample<T>::Sample (T aNum[5]) { for(int i=0; i<5; i++) num[i]= aNum[i]; }template<class T> T Sample<T>::getSum() { T total = 0; for(int i=0; i<5; i++) total = total + num[i]; return total; } int main() { int x[5]={8, 6, 4, 7, 10}; double y[5]={8.8, 6.6, 4.4, 7.7, 10.1}; Sample<int> Obj(x); //When you want to use a template class, you specify a data type. Sample<double> Obj2(y); cout<<"The sum of first object is "<<Obj.getSum()<<endl; cout<<"Sum for 2nd object is "<<Obj2.getSum()<<endl; system("pause"); return 0; }