Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Sign in / Register
Toggle navigation
Menu
Open sidebar
Clark Lin
StudyCpp
Commits
06e83b5a
Commit
06e83b5a
authored
Nov 27, 2022
by
Administrator
Browse files
add generics
parent
aacaddcf
Changes
1
Hide whitespace changes
Inline
Side-by-side
03.Advanced/Generics.cpp
0 → 100644
View file @
06e83b5a
#include <iostream>
using
namespace
std
;
// 使用模板定义泛型函数
// 模板在编译时会进行扩展,编译器会检查扩展的需求
// 代码里的一个函数,编译后可能产生多个copy。
// 定义泛型类型T
// 使用泛型类型定义泛型函数
template
<
typename
T
>
T
myMax
(
T
x
,
T
y
)
{
return
(
x
>
y
)
?
x
:
y
;
}
// 定义泛型类
template
<
typename
T
>
class
Array
{
private:
T
*
ptr
;
int
size
;
public:
Array
(
T
arr
[],
int
s
);
void
print
();
};
template
<
typename
T
>
Array
<
T
>::
Array
(
T
arr
[],
int
s
)
{
// 动态分配内存给指针,分配内存的大小根据实际类型和数组长度决定
ptr
=
new
T
[
s
];
size
=
s
;
for
(
int
i
=
0
;
i
<
size
;
i
++
)
{
// 指针数组的每个成员都指向实际数组的每个成员的地址
ptr
[
i
]
=
arr
[
i
];
}
}
template
<
typename
T
>
void
Array
<
T
>::
print
()
{
// 循环指针数组的每个成员
for
(
int
i
=
0
;
i
<
size
;
i
++
)
{
// 打印每个指针成员指向的地址的实际值
cout
<<
" "
<<
*
(
ptr
+
i
);
// cout << " " << ptr[i]; // 和上面一行等价
}
cout
<<
endl
;
}
int
main
()
{
// 编译器根据这句语句,定义名为“int myMax(int x, int y)”的函数
cout
<<
myMax
<
int
>
(
3
,
7
)
<<
endl
;
// Call myMax for int
// 编译器根据这句语句,定义名为“double myMax(double x, double y)”的函数
cout
<<
myMax
<
double
>
(
3.1
,
7.1
)
<<
endl
;
// call myMax for double
// 编译器根据这句语句,定义名为Array的类,并在其中定义名为“char myMax(char x, char y)”的函数
cout
<<
myMax
<
char
>
(
'g'
,
'e'
)
<<
endl
;
// call myMax for char
int
arr
[
5
]
=
{
1
,
2
,
3
,
4
,
5
};
// 编译器根据这句语句,定义名为“Array(int arr[], int s)”的构造函数
Array
<
int
>
a
(
arr
,
5
);
a
.
print
();
return
0
;
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment