可以使用數(shù)組下標操作符 ([ ]) 訪問數(shù)組的各個元素。 如果在無下標表達式中使用一維數(shù)組,組名計算為指向該數(shù)組中的第一個元素的指針。
// using_arrays.cppint 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.}
使用多維數(shù)組時,在表達式中使用各種組合。
// 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 的一個三維數(shù)組。 p2multi 指針指向大小為三的 double 類型數(shù)組。 本例中該數(shù)組用于一個,兩個和三個下標。 盡管指定所有下標更為常見(如 cout 語句所示),但是如下的語句 cout 所示,有時其在選擇數(shù)組元素的特定子集時非常有用。
初始化數(shù)組
如果類具有構(gòu)造函數(shù),該類的數(shù)組將由構(gòu)造函數(shù)初始化。如果初始值設(shè)定項列表中的項少于數(shù)組中的元素,則默認的構(gòu)造函數(shù)將用于剩余元素。如果沒有為類定義默認構(gòu)造函數(shù),初始值設(shè)定項列表必須完整,即數(shù)組中的每個元素都必須有一個初始值設(shè)定項。
考慮定義了兩個構(gòu)造函數(shù)的Point 類:
// initializing_arrays1.cppclass 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 的第一個元素是使用構(gòu)造函數(shù) Point( int, int ) 構(gòu)造的;剩余的兩個元素是使用默認構(gòu)造函數(shù)構(gòu)造的。
靜態(tài)成員數(shù)組(是否為 const)可在其定義中進行初始化(類聲明的外部)。例如:
// initializing_arrays2.cppclass 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(){}
表達式中的數(shù)組
當數(shù)組類型的標識符出現(xiàn)在 sizeof、address-of (&) 或引用的初始化以外的表達式中時,該標識符將轉(zhuǎn)換為指向第一個數(shù)組元素的指針。 例如:
char szError1[] = "Error: Disk drive not ready.";char *psz = szError1;
指針 psz 指向數(shù)組 szError1 的第一個元素。 請注意,與指針不同,數(shù)組不是可修改的左值。 因此,以下賦值是非法的:
szError1 = psz;