可以使用數組下標操作符 ([ ]) 訪問數組的各個元素。 如果在無下標表達式中使用一維數組,組名計算為指向該數組中的第一個元素的指針。
// 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.}
使用多維數組時,在表達式中使用各種組合。
// 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.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 的第一個元素是使用構造函數 Point( int, int ) 構造的;剩余的兩個元素是使用默認構造函數構造的。
靜態成員數組(是否為 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(){}
表達式中的數組
當數組類型的標識符出現在 sizeof、address-of (&) 或引用的初始化以外的表達式中時,該標識符將轉換為指向第一個數組元素的指針。 例如:
char szError1[] = "Error: Disk drive not ready.";char *psz = szError1;
指針 psz 指向數組 szError1 的第一個元素。 請注意,與指針不同,數組不是可修改的左值。 因此,以下賦值是非法的:
szError1 = psz;