1. 函数与数组
大多数情况下,C++与C语言一样,将数组名视为指针,C++将数组名解释为数组第一个元素的地址,即arr == &arr[0]。但存在一些例外情况:首先,数组声明使用数组名来标记数组存储的位置;其次,将sizeof运算符作用于数组将得到整个数组的长度(单位为字节);再者,对数组名取地址(将地址运算符&作用于数组名)将会得到整个数组的地址,若定义 int cookies[8] = {}; 则&cookies将返回一个32字节内存块的地址(假设int占4字节)。
(1)数组函数使用示例(重点关注使用cin得到坏输入时如何重启输入)
// 房地产
#include <iostream>
using namespace std;
const int Max = 5;
int fill_array(double ar[], int limit);
void show_array(const double ar[], int n);
void revalue(double r, double ar[], int n);
int main() {
double properties[Max];
int size = fill_array(properties, Max);
show_array(properties, size);
if (size > 0) {
cout << "Enter revaluation factor: ";
double factor;
while (!(cin >> factor)) {
// bad input
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Bad input, please enter a number: ";
}
revalue(factor, properties, size);
show_array(properties, size);
}
cout << "Done.\n";
cin.get();
cin.get();
return 0;
}
// 填充数组
int fill_array(double ar[], int limit) {
double temp;
int i;
for (i = 0; i < limit; i++) {
cout << "Enter value #" << i + 1 << ": ";
cin >> temp;
if (!cin) {
// bad input
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Bad input, input process terminated.\n";
break;
}
else if (temp < 0) {
cout << "i = " << i << endl;
break;
}
ar[i] = temp;
}
cout << "i = " << i << endl;
return i;
}
// 显示数组
void show_array(const double ar[], int n) {
for (int i = 0; i < n; i++) {
cout << "Property #" << i + 1 << ": $";
cout << ar[i] << endl;
}
}
// 修改数组
// 将每个元素与同一个重新评估因子相乘
void revalue(double r, double ar[], int n) {
for (int i = 0; i < n; i++)
ar[i] *= r;
}
(2)使用数组区间的函数示例
// 使用数组区间的函数
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int ArSize = 8;
int sum_arr(const int* begin, const int* end);
int main() {
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 += *pt;
}
return total;
}
(3)指针和const
仅当只有一层间接关系(如指针指向基本数据类型)时,才可以将非const地址或指针赋给const指针。如果条件允许,则应当将指针形参声明为指向const的指针(即尽量使用const)。
2. 函数与C风格字符串
(1)将C风格字符串作为参数的函数