详解C++编程中数组的基本用法

可以使用数组下标操作符 ([ ]) 访问数组的各个元素。 如果在无下标表达式中使用一维数组,组名计算为指向该数组中的第一个元素的指针。

// using_arrays.cpp
int main() {
 char chArray[10];
 char *pch = chArray; // Evaluates to a pointer to the first element.
 char ch = chArray[0]; // Evaluates to the value of the first element.
 ch = chArray[3]; // Evaluates to the value of the fourth element.
}

使用多维数组时,在表达式中使用各种组合。

// using_arrays_2.cpp
// compile with: /EHsc /W1
#include <iostream>
using namespace std;
int main() {
 double multi[4][4][3]; // Declare the array.
 double (*p2multi)[3];
 double (*p1multi);

 cout << multi[3][2][2] << "\n"; // C4700 Use three subscripts.
 p2multi = multi[3];    // Make p2multi point to
          // fourth "plane" of multi.
 p1multi = multi[3][2];   // Make p1multi point to
          // fourth plane, third row
          // of multi.
}

在前面的代码中, multi 是类型 double 的一个三维数组。 p2multi 指针指向大小为三的 double 类型数组。 本例中该数组用于一个,两个和三个下标。 尽管指定所有下标更为常见(如 cout 语句所示),但是如下的语句 cout 所示,有时其在选择数组元素的特定子集时非常有用。

初始化数组
如果类具有构造函数,该类的数组将由构造函数初始化。如果初始值设定项列表中的项少于数组中的元素,则默认的构造函数将用于剩余元素。如果没有为类定义默认构造函数,初始值设定项列表必须完整,即数组中的每个元素都必须有一个初始值设定项。
考虑定义了两个构造函数的Point 类:

// initializing_arrays1.cpp
class Point
{
public:
 Point() // Default constructor.
 {
 }
 Point( int, int ) // Construct from two ints
 {
 }
};

// An array of Point objects can be declared as follows:
Point aPoint[3] = {
 Point( 3, 3 )  // Use int, int constructor.
};

int main()
{
}

aPoint 的第一个元素是使用构造函数 Point( int, int ) 构造的;剩余的两个元素是使用默认构造函数构造的。
静态成员数组(是否为 const)可在其定义中进行初始化(类声明的外部)。例如:

// initializing_arrays2.cpp
class WindowColors
{
public:
 static const char *rgszWindowPartList[7];
};

const char *WindowColors::rgszWindowPartList[7] = {
 "Active Title Bar", "Inactive Title Bar", "Title Bar Text",
 "Menu Bar", "Menu Bar Text", "Window Background", "Frame" };
int main()
{
}

表达式中的数组
当数组类型的标识符出现在 sizeof、address-of (&) 或引用的初始化以外的表达式中时,该标识符将转换为指向第一个数组元素的指针。 例如:

char szError1[] = "Error: Disk drive not ready.";
char *psz = szError1;

指针 psz 指向数组 szError1 的第一个元素。 请注意,与指针不同,数组不是可修改的左值。 因此,以下赋值是非法的:

szError1 = psz;