详解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 所示,有时其在选择数组元素的特定子集时非常有用。 初始化数组 // 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 ) 构造的;剩余的两个元素是使用默认构造函数构造的。 // 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() { } 表达式中的数组 char szError1[] = "Error: Disk drive not ready."; char *psz = szError1; 指针 psz 指向数组 szError1 的第一个元素。 请注意,与指针不同,数组不是可修改的左值。 因此,以下赋值是非法的: szError1 = psz; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |