函式模板的應用。

2021-08-14 04:09:45 字數 702 閱讀 4433

看了普拉達的c++書,然後看到第8章的程式設計習題,自己編了乙個程式,主要實現以下功能:利用函式模板知識,編寫乙個求得最大值得函式模板,對於輸入的double型或者int型都能夠適用,然後再編寫乙個過載的具體化模板,實現,輸入有限個字串,並且以指標字串和指標數量,作為形參,並且返回最長字串的位址。

#include

#include

#include

using namespace std;

template

t max5(t arr, int n)

return (max);

}template <>char *max5(char *a, int n)

}return p;

}int main()

int c=max5(a, 5);

cout << "the max is "<> e[i];

}double d = max5(e, 5);

cout << "the max is" << d << endl;

cout << "please input five zifuchuan:\n";

char *b[5];

for(int i=0;i<5;i++)

cout <<"the max zifuchuan is:"<< max5(b, 5) << endl;

return 0;

}

函式模板的應用

利用函式模板,可以適應傳遞引數的多種資料型別。既可以實現過載函式的多型性,又能避免寫多個同名函式的繁瑣龐雜 例 定義乙個模板函式cad,實現兩個引數數的相加或者字串的連線。include includetemplaten cad n a1,n a2 int main 執行結果如圖 在本例當中,申明了...

模板 函式模板

c 程式設計 資料結構與程式設計方法 例15.8 利用函式過載技術,求兩個整數 字元 浮點數或字串中的較大值,需要編寫4個函式larger。而c 通過提供函式模板,簡化了過載函式據的過程。include using namespace std template type,模板的形參,用於確定函式的形...

函式模板和模板函式

1.函式模板的宣告和模板函式的生成 1.1函式模板的宣告 函式模板可以用來建立乙個通用的函式,以支援多種不同的形參,避免過載函式的函式體重複設計。它的最大特點是把函式使用的資料型別作為引數。函式模板的宣告形式為 template 返回型別 函式名 參數列 其中,template是定義模板函式的關鍵字...