函數原型:
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