c++/oop---類模板
阿新 • • 發佈:2022-03-31
c++/oop---類模板
定義出一批相似的類, 可以定義類模板, 然後由類模板生成不同的類
例:可變長整型陣列
寫法:
template <型別引數表(class 型別引數1,class 型別引數2...)>
class 模板名{
....
};
類模板中的成員函式在外面定義時:
template <型別引數表(class 型別引數1,class 型別引數2...)>
返回值型別 類模板名<型別引數名列表>::成員函式名(引數表)
{
...
}
定義物件:
類模板名<真實型別引數表>物件名(建構函式實際引數);
編譯器由類模板生成類的過程叫類模板的例項化。由類模板例項化得到的類,叫模板類。
同一個類模板的兩個模板類是不相容的
#include <iostream> using namespace std; template <class T> class A { public: int num; A (int n):num(n){} template<class T2> void Func(T2 t) { for(int i=1;i<=num;i++) cout << t << endl; } }; int main() { A<int> a(5); a.Func('K'); a.Func("hello"); return 0; } /* K K K K K hello hello hello hello hello */