您的位置:首页 > 编程语言 > C语言/C++

An easy instance of using the template class in C++

2007-02-01 21:49 796 查看
//this is the source code

#include<iostream>

using namespace std;
template<class datatype>class basis{ //set the template class with parameters
public:
void swap(datatype*,datatype*);
void printv(datatype,datatype);
}; //Never lose the stub after a class's definition
/*******************************
* What's more, in the Object *
* orientied c++ programming, *
* a template can have its 8 *
* argument and parameters *
* its arguments can be also a *
* class or so. Thus we can *
* write the parameter in a <>.*
* In the following steps, if *
* we write its member *
* functions we have to write *
* like this. *
* *****************************/

template<class datatype> //if we want to call the function in a template class we should add in this header line!!!
void basis<datatype>::swap(datatype *firstnum,datatype *secondnum)
{
datatype temp;
temp=*firstnum;
*firstnum=*secondnum;
*secondnum=temp;
}
/**********************************************************
* If we wanna swap the values of two variables, we have *
* numerious of methods. But the basic method is to swap *
* the values by referrence. *
**********************************************************/
template<class datatype>
void basis<datatype>::printv(datatype first,datatype second)
{
cout<<"The value is "<<first<<"and "<<second<<"now."<<endl;
}
//All the code above can be written in a head file
int main()
{
basis<int>intpair; //call the template class and give the variable
/***********************************
* The data type is also a kind of *
* class, see how we call the *
* template class and *
* its parameters! *
***********************************/
int inta=1,intb=2;
intpair.printv(inta,intb);
intpair.swap(&inta,&intb);
intpair.printv(inta,intb);

basis<float>fpair;
float fa=0.1,fb=0.2;
fpair.printv(fa,fb);
fpair.swap(&fa,&fb);
fpair.printv(fa,fb);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐