2. 例子說明(類別樣板) test1.cpp
#include
<iostream.h>
#include <stdlib.h>
template <class type>
class Cmax
{
public:
type max(type x1, type x2);
};
template <class type>
type Cmax<type>::max(type x1, type x2)
{
if(x1>x2){
return(x1);
}
return(x2);
}
void main( )
{
int answer1;
double answer2;
Cmax<int> obj1;
Cmax<double> obj2;
answer1=obj1.max(3, 5);
answer2=obj2.max(4.5, 6.7);
cout<<answer1<<endl;
cout<<answer2<<endl;
return;
} |
(1) <class
type> 告訴C++,type可用任何型態取代。
(2) 可將類別樣板想成
template <class
type>
class Cname
{
public:
type function(...);
};template <class type>
type Cname<type>::function(...)
{
...
}
void main()
{
Cname<int> obj;
...
return;
} |
|