函数模板与类模板
1.类模板
View Code
1 #include <iostream> 2 3 using namespace std; 4 5 template<typename T> 6 class CA 7 { 8 public: 9 CA(T v) 10 { 11 value = v; 12 } 13 14 void SetValue(T v) 15 { 16 value = v; 17 } 18 19 T GetValue() 20 { 21 return value; 22 } 23 24 private: 25 T value; 26 }; 27 28 int main() 29 { 30 CA<double> a(9.5); 31 cout<<"a.value:"<<a.GetValue()<<endl; 32 a.SetValue(10.5); 33 cout<<"a.value:"<<a.GetValue()<<endl; 34 35 return 0; 36 }
2.函数模板
View Code
1 #include <iostream> 2 3 using namespace std; 4 5 template<typename T> 6 T max(T a, T b) 7 { 8 return (a>b)?a:b; 9 } 10 11 int main() 12 { 13 int x=2,y=6; 14 double a=9.1,b=12.6; 15 cout<<"int:"<<max(x,y)<<endl; 16 cout<<"double:"<<max(a,b)<<endl; 17 18 return 0; 19 }
posted on 2012-05-10 10:01 ActiveChange 阅读(156) 评论(0) 编辑 收藏 举报