1,数组的类型
T D1[constant_Expre-ssions];
数组的元素可以是任意类型,但不能是引用、void类型、函数类型或者抽象类(只能用作基类的类)类型。
标准原文:
T is called the array element type; this type shall not be a reference type, the
(possibly cv-qualified) type void, a function type or an abstract class type.
比如,如果定义:
void vo_arr[5];
则会报: error C2182: “vo_arr”: 非法使用“void”类型
如果定义:
int& ref_arr[5];
则会报:error C2234: “ref_arr”: 引用数组是非法的
但是,如果你定义了一个普通数组,但是用引用来给其中的元素赋值则完全没有问题。
比如:
int i = 0;
int &ref1 = i;
int &ref2 = i;
int &ref3 = i;
int arr[] = {ref1, ref2, ref3};
虽然数组arr中的每个元素都是用引用赋值的,但完全不会报错,因为ref1、ref2和ref3都不过是i的别名,跟直接用i来赋值没有区别。
2,数组长度
T D1[constant_Expre-ssions];
constant_Expre-ssions是常量表达式的意思,即必须要在编译阶段就知道具体的值,而不能等到运行阶段才知道值。
可以是:整型字面值常量、枚举常量或者用常量表达式初始化的整型const对象。
整型字面值常量和枚举常量都很常见,需要注意的是整型const对象。
并不是每个const int都能用作数组长度,而必须是用常量表达式初始化的才行。
比如:
const unsigned sz = 3; //可以用作数组长度
const unsigned sz = get_size(); //不可以用作数组长度,到编译时才知道其数值
int a = 5; //不可用作数组长度
3,size_t
数组下标的类型是size_t
而vector下标的类型是:vector<T>::size_type
定义在cstddef中