用函数模板匹配内置数组
这是我在看《程序设计原理与实践(第二版)(进阶篇)》中学习Matrix库相关内容的时候看到的一个知识点。
#include<iostream>
using namespace std;
template<class T, int n>
void test(const T(&a)[n]) { //这是一个重点:数组的引用。这是C++才有的特性,C中没有
// (&a) 这里的括号是必须有的。
for (int i = 0; i < n; i++)
cout << a[i] << '\t';
cout << endl;
}
int main() {
int a[]{ 1,2,3,4,5 }; //编译器能够推断出已经初始化的数组的规模
test(a);
return 0;
}
数组知识补充:
数组有两个特性,主要在需要用数组作为参数传递时体现:一是不能复制数组;二是使用数组名时,数组名就相当于指向数组的第一个元素的指针(实际就是这样)。因为不能复制,所以无法编写使用数组类型的形参,数组会自动转化为指针。
#include<iostream>
using namespace std;
void test(int a[5]) { //自动转化为指向第一个元素的指针
*a = 11;
cout << a[0] << endl; //输出11
}
int main() {
int a[]{ 1,2,3,4,5 };
test(a);
cout << a[0] << endl; //输出11
return 0;
}