一、模板類的說明
模板類有一個好處是可以放寬你輸入的數據類型。
比如有這樣的一個函數:
int add(int x, int y) { return x+y; }
這個函數對於int類型的x,y才適合,但是如果我們希望計算float類型的呢?
這必須重新定義一個函數(函數重載也可以實現)
float add(float x, float y) { return x+y; }
但是這樣顯然太麻煩,所以模板類可以解決這個問題
二、一個例子
書上的一個例子用作說明
#include <iostream> using namespace std; template <typename Type> //這一步說明了你要定義一個模板類,數據類型名字是Type(比如可能是int, float,等等) class Calc { public: Calc (); Type multiply (Type x, Type y);//類型都是Type Type add (Type x, Type y);//這里是函數的聲明 }; template <typename Type> Calc<Type>::Calc () { } template <typename Type> Type Calc<Type>::multiply (Type x, Type y) { return x * y; } template <typename Type> Type Calc<Type>::add (Type x, Type y)//這里是函數定義 { return x+y; } int main(void) { Calc<int> person; int m=3; int n=2; int sum=person.add(m,n); cout<<"the result is "<<sum<<endl; return 0; }
三、運行錯誤
最開始初始化的時候,我是這樣寫的:
Calc person;
但是失敗了,結果如下:
后來查了一下,發現需要在初始化的時候傳入一個數據類型,告訴程序你要存儲什么數據。
有人給了一個解答:
https://stackoverflow.com/questions/33413084/missing-template-arguments-before-l
截圖如下:
講的很透徹^-^