c++之类模板

类模板:

格式:

1. 声明
template<typename T>
class AAA {
/* 使用T表示某种类型,比如: */
private:
T obj;
public:
void test_func(T& t);
.....
};

2. 定义
template<typename

T>
void AAA<T>::test_func(T& t) { .... }

使用:

1.用到时再实例化:
AAA<int> a;
AAA<double> b;

2.事先实例化:

template AAA<int>;
再使用:
AAA<int> a;

定做(类似重载):

1. 声明
template<>
class AAA<int> {
......
public:
void test(void);
};

2. 定义
void AAA<int>::test(void) {...}

 1 #include <iostream>
 2 #include <string.h>
 3 #include <unistd.h>
 4 
 5 using namespace std;
 6 
 7 template <typename T>
 8 class AAA{
 9 private:
10     T t;
11 public:
12     void test_func(const T &t);
13     void print(void);
14 
15 
16 };
17 
18 template<typename T>
19 void AAA<T>::test_func(const T &t)
20 {
21     this -> t = t;
22 }
23 
24 template<typename T>
25 void AAA<T>::print(void)//注意T
26 {
27     cout<<t<<endl;
28 }
29 
30 int main(int argc,char ** atgv)
31 {
32     AAA<int> a;//用到时再实例化
33     a.test_func(1);
34     a.print();
35 }
View Code

运行结果:

1

 1 #include <iostream>
 2 #include <string.h>
 3 #include <unistd.h>
 4 
 5 using namespace std;
 6 
 7 template <typename T>
 8 class AAA{
 9 private:
10     T t;
11 public:
12     void test_func(const T &t);
13     void print(void);
14 
15 
16 };
17 
18 template<typename T>
19 void AAA<T>::test_func(const T &t)
20 {
21     this -> t = t;
22 }
23 
24 template<typename T>
25 void AAA<T>::print(void)//注意T
26 {
27     cout<<t<<endl;
28 }
29 
30 template <>
31 class AAA<int>{
32 public:
33     void test_func_int(const int &t)
34     {
35         cout<<t<<endl;
36     }
37     void print_int(void);
38 
39 };
40 
41 void AAA<int>::print_int(void)
42 {
43     cout<<"for test"<<endl;
44 }
45 
46 int main(int argc,char ** atgv)
47 {
48     AAA<double> a;//用到时再实例化
49     a.test_func(1);
50     a.print();
51 
52     AAA <int>b;//函数实现了定制,尖括号就要用定制时的尖括号中的类型
53 
54     b.test_func_int(1);
55     b.print_int();
56 }
View Code

运行结果:

1

1

for test

猜你喜欢

转载自www.cnblogs.com/yekongdebeijixing/p/12173843.html