函数原型:
0. 函数原型就是 放在int前面声明函数名称,传参类型和返回类型的一个语句
1. 为什么需要函数原型
2. 原型的语法:
returntype functionname(typename);
3.原型的功能:
简单的数据类型 正常是按值传递。 而复杂数据类型就是按引用传递
int sum = sum_arr(int arr[], int n) 这边的arr[] 不一定指的是数组 也可以是指针 或者数组的第一个元素的地址 其实可以换成 int* arr
在7.6de arrfun2.cpp这个代码中要注意一个地方跟书上有出入
#include <iostream>
const int ArSize = 8;
int sum_arr(int arr[], int n);
int main()
{
int cookies[ArSize] = {1, 2, 4, 8, 16, 32, 64, 128};
std::cout << cookies << " = array address, ";
std::cout << sizeof cookies << " = sizeof cookies\n";
int sum = sum_arr(cookies, ArSize);
std::cout << "Total cookies eatenl: " << sum << std::endl;
sum = sum_arr(cookies, 3);
std::cout << "First three eaters ate " << sum << " cookies.\n";
sum = sum_arr(cookies + 4, 4);
std::cout << "Last four eaters ate " <<sum << " cookies.\n";
return 0;
}
int sum_arr(int arr[], int n)
{
int total = 0;
std::cout << arr << " = arr, ";
// 这里 书上是不带‘&’号 但是我的编译器会报错 6.3版本
std::cout << sizeof &arr << " = sizeof arr\n";
for (int i = 0; i < n; i++)
total = total + arr[i];
return total;
}
使用数组区间来传递数组的首尾位置
#include <iostream>
const int ArSize = 8;
int sum_arr(const int* begin, const int* endl);
int main()
{
using namespace std;
int cookies[ArSize] = {1, 2, 4, 8, 16, 32, 64, 128};
int sum = sum_arr(cookies, cookies + ArSize);
cout << "Total cookies eaten: " << sum << endl;
sum = sum_arr(cookies, cookies + 3);
cout << "First three eaters ate " << sum << " cookies.\n";
sum = sum_arr(cookies + 4, cookies + 8);
cout << "Last four eaters ate " << sum << " cookies.\n";
return 0;
}
int sum_arr(const int* begin, const int* end)
{
const int* pt;
int total = 0;
for (pt = begin; pt !=end; pt++)
total = total + *pt;
return total;
}
先到这今天 明天继续 指针和const