复制代码
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109#include <iostream> #include <string> template <typename T> void Swap(T &, T &); template <typename T> void Swap(T[], T[], int); void show (int *, int n); struct student; template <> void Swap<student>(student &s1, student &s2); void showstu(const student &); //模板函数只是给出了一个生成函数定义的方案,并没有定义函数,函数的定义是由编译器完成的 //对于一个函数名,可以有如下几个版本 //非模板函数 //模板函数 //模板的函数的显示具体化 //以上三个的重载版本 //调用优先级非模板函数 > 显示具体化模板函数 > 模板函数 //根据传入参数类型的不同,生成相应的版本,这个过程叫做实例化 //显示具体化和隐式具体化统称为实例化 struct student { int id; double grade; std::string name; }; int main() { using namespace std; int a,b; double x,y; string p,t; cout << "please input a(int) and b(int)"; cin >> a >> b; cout << "now a is " << a << " b is " << b <<endl; Swap(a,b); cout << "function Swap after " << "a is " << a << " b is " << b <<endl; cout << "please input x(double) and y(double)"; cin >> x >> y; cout << "now x is " << x << "y is " << y <<endl; Swap(x,y); cout << "function Swap after " << "x is " << x << " y is " << y <<endl; cout << "please input p(string) and t(string)"; cin >> p >>t; cout << "now p is " << p << "t is " << t; Swap(p,t); cout << "function Swap after " << "p is " << p << " t is " << t; cout << "n模板类重载" <<endl; int num1[] {1,2,3,4,5}; int num2[] {5,4,3,2,1}; show(num1, 5); cout << endl; show(num2, 5); cout << "Swap after " <<endl; Swap(num1,num2,5); show(num1,5); cout << endl; show(num2,5); cout << "n具体化 " <<endl; student s1{20215014,91.5,"wang"}, s2{20215066,96.4,"zhang"}; showstu(s1); showstu(s2); Swap(s1,s2); showstu(s1); showstu(s2); return 0; } template <typename T> void Swap(T &a,T &b) { T temp; temp = a; a = b; b = temp; } template <typename T> void Swap(T a[], T b[],int n) { int temp; for(int i=0;i<n;i++){ temp = a[i]; a[i] = b[i]; b[i] = temp; } } void show(int *a, int n) { for(int i=0;i<n;i++){ std::cout << a[i] << " "; } } void showstu(const student &s) { std::cout << "idt" << "gradet" << "name" <<std::endl; std::cout << s.id << "t" << s.grade << "t" << s.name << std::endl; } //具体化的声明需要<type_name>但是模板函数的实现可以不用 template <> void Swap(student &s1, student &s2) { double t1; int t2; t1 = s1.grade; s1.grade = s2.grade; s2.grade = t1; t2 = s1.id; s1.id = s2.id; s2.id = t2; }
最后
以上就是拼搏皮带最近收集整理的关于C++模板与模板的重载的全部内容,更多相关C++模板与模板内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复