一、函数模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <cstdlib> #include <iostream> using namespace std; template<class t=""> T add(T a,T b) { return a+b; } int main(int argc, char** argv) { int a=2,b=3; float c=1.23,d=2.34; cout<<add(a,b)<<endl; cout<<add(c,d)<<endl;="" system("pause");="" return="" 0;="" }<="" pre=""> 运行结果: <pre lang="text" line="1">NPP_EXEC: "GCC_Run" funtemplate.exe Process started >>> 5 3.57 请按任意键继续. . . <<< Process finished. |
二、类模板
(1)类模板的具体格式
1 2 3 4 5 |
template <class t=""> class A { } </class> |
在类定义体外定义的成员函数,应该使用函数模板。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
#include <cstdlib> #include <iostream> using namespace std; template <class t=""> class Add { public: Add(T da,T db) { a=da;b=db; } T out() { T c; c=a+b; return c; } private: T a,b; }; int main() { Add <int> a(2,3); cout<<a.out()<<endl; add="" <float=""> b(2.22,1.22); cout<<b.out()<<endl; system("pause");="" return="" 0;="" }="" <="" pre=""> <pre lang="text" line="1">NPP_EXEC: "GCC_Run" funclass.exe Process started >>> 5 3.44 请按任意键继续. . . <<< Process finished. |
在类外定义成员函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#include <cstdlib> #include <iostream> using namespace std; template <class t=""> class Add { public: Add(T da,T db) { a=da;b=db; } T out(); private: T a,b; }; template </class><class t=""> //使用函数模板 T Add<t>::out() { T c; c=a+b; return c; } int main() { Add <int> a(2,3); cout<<a.out()<<endl; add="" <float=""> b(2.22,1.22); cout<<b.out()<<endl; system("pause");="" return="" 0;="" }="" <="" pre=""></b.out()<<endl;></a.out()<<endl;></int></t></class></iostream></cstdlib> |
发表回复