C++ 数组作为函数参数示例:
#include <iostream>
static void print(const int* beg, const int* end)
{
while (beg != end)
{
std::cout << *beg++ << std::endl;
}
}
static void print(const int* arr, const size_t size)
{
for (size_t i = 0; i != size; ++i)
{
std::cout << arr[i] << std::endl;
}
}
// 数组引用形参
static void print(int(&arr)[2])
{
/*note:
f(int& arr[2]) // 错误:将 arr 声明成引用的数组
f(int (&arr)[2] // 正确: arr 是具有10个整数的整型数组的引用
*/
for (auto elem : arr)
{
std::cout << elem << std::endl;
}
}
int main()
{
int j[2] = { 0, 1 };
std::cout << "遍历方式一" << std::endl;
print(std::begin(j), std::end(j));
std::cout << "遍历方式二" << std::endl;
print(j, std::end(j) - std::begin(j));
std::cout << "数组引用形参" << std::endl;
print(j);
return 0;
}
输出:
遍历方式一
0
1
遍历方式二
0
1
数组引用形参
0
1
参考:《C++ Primer》 P196 标签:const,示例,int,C++,函数参数,数组 From: https://www.cnblogs.com/huvjie/p/18308726