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

    技术2022-05-11  71

    //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 fileint 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;}


    最新回复(0)