cppTest-3.5:模板函數

/**
 *cppTest-3.5:模板函數
 *
 *author 煒sama
 */
#include<iostream.h>
#include<conio.h>
#include<string.h>

template<class Type>//說明Type是一個類型,在接下來的代碼中將會使用這個類型
//int i=0;//測試發現這裏不能插入任何代碼!!
Type max(Type v1,Type v2)//使用上面定義的類型來定義函數
{
    return v1>v2?v1:v2;
}

char *max(char *x,char *y)//(1)與上面的模板函數同名的一般函數,調用的順序是一般函數優先!
{
    return strcmp(x,y)>0?x:y;
}

template<class T>
void div(T v1,T v2){
	cout<<"v1:"<<v1<<",v2:"<<v2<<",v1/v2:"<<v1/v2<<endl;
}

void main()
{
	int m1=max(100,300);
    double m2=max(32.1,3.14);
    char *m3=max("Zhang", "Li");
    cout<<"The maxium of 100 and 300 is:"<<m1<<endl;
    cout<<"The maxium of 32.1 and 3.14 is:"<<m2<<endl;
    cout<<"The maxium of Zhang and Li is:"<<m3<<endl;//如果沒有上面的(1),這裏返回的結果是錯的!
    
	div(5.0,2.0);//第一個參數5.0把T實例化爲double型,那第二個參數也必須是double型,否則報錯。例如爲2,2不會自動轉型爲double!報錯!
	//div(5,2.0);//報錯!
	//div(5.0,2);//報錯!
	div(5.0f,2.0f);
	//div(5.0,2.0f);//報錯!
	//div(5.0f,2.0);//報錯!
	div(1,1);
	div(5,2);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章