一切尽在代码中:
/*
* =====================================================================================
*
* Filename: 1.cc
*
* Description: 一般向数组传递参数都是传数组名(实际上在函数参数中被转换为指向第一个
* 元素的指针)和数组的大小,但是可以向函数只传递一个参数,达到近似或者
* 同样的目的。
*
* Version: 1.0
* Created: 2013年04月15日 14时45分42秒
* Revision: none
* Compiler: gcc
*
* Author: XXL
* Organization:
*
* =====================================================================================
*/
#include <iostream>
#define MAXSIZE 10
using std::cout;
using std::endl;
struct Array
{
int a[MAXSIZE];
//这里大有可说!对于类的数组成员,不允许使用初始化列表,因为初始化列表不支持数组下标
//运算,故实际上只能在构造函数体中使用赋值,在效率上,对元素类型为内置类型的数组没有
//影响,但是对于类类型的数组,要先执行其默认构造函数,然后再进行重载的赋值操作,故效
//率会降低。更重要的问题出来了,既然出现了执行默认构造函数,那么这个数组元素(即类类
//型的对象)一定要有默认的构造函数,否则会出错。
Array()
{
for (int i = 0; i < MAXSIZE; i++)
a[i] = i;
}
};
//算是利用面向对象封装的思想吧,有点耍赖皮的意思。
void func1(const Array &array)
{
cout << "func1:" << endl;
for (int i = 0; i < MAXSIZE; ++i)
cout << array.a[i] << " ";
cout << endl << endl;
}
//利用了C++的语言特性——引用。但是此法的缺陷是,只能向函数传递大小为MAXSIZE的数组
void func2(int (&a)[MAXSIZE])
{
cout << "func2:" << endl;
for (int i = 0; i < MAXSIZE; ++i)
cout << a[i] << " ";
cout << endl << endl;
}
//这是最好的方法,利用了模板的非类型形参,参考了primer第533页,取消了类型形参T,
//此处只用int型。需要特别注意的!!!!!
//函数形参必须声明为数组的引用,若是int a[n],则忽略了n,把参数当成指向int的指针,
//即int*类型,调用func3(a)时,会提示错误:实参类型为数组类型,而不是int*,
// 特注:此方法也可用来实现返回数组长度的方法
template<int n>
void func3(int (&a)[n]) // not "int a[n]"
{
cout << "func3:" << endl;
for (int i = 0; i < MAXSIZE; ++i)
cout << a[i] << " ";
cout << endl << endl;
}
int main()
{
Array array;
array.a[0] = 100;
func1(array);
int a[MAXSIZE] = {200};
func2(a);
a[0] = 333;
func3(a);
return 0;
}