详解C++编程中数组的基本用法
可以使用数组下标操作符([])访问数组的各个元素。如果在无下标表达式中使用一维数组,组名计算为指向该数组中的第一个元素的指针。
//using_arrays.cpp intmain(){ charchArray[10]; char*pch=chArray;//Evaluatestoapointertothefirstelement. charch=chArray[0];//Evaluatestothevalueofthefirstelement. ch=chArray[3];//Evaluatestothevalueofthefourthelement. }
使用多维数组时,在表达式中使用各种组合。
//using_arrays_2.cpp //compilewith:/EHsc/W1 #include<iostream> usingnamespacestd; intmain(){ doublemulti[4][4][3];//Declarethearray. double(*p2multi)[3]; double(*p1multi); cout<<multi[3][2][2]<<"\n";//C4700Usethreesubscripts. p2multi=multi[3];//Makep2multipointto //fourth"plane"ofmulti. p1multi=multi[3][2];//Makep1multipointto //fourthplane,thirdrow //ofmulti. }
在前面的代码中,multi是类型double的一个三维数组。p2multi指针指向大小为三的double类型数组。本例中该数组用于一个,两个和三个下标。尽管指定所有下标更为常见(如cout语句所示),但是如下的语句cout所示,有时其在选择数组元素的特定子集时非常有用。
初始化数组
如果类具有构造函数,该类的数组将由构造函数初始化。如果初始值设定项列表中的项少于数组中的元素,则默认的构造函数将用于剩余元素。如果没有为类定义默认构造函数,初始值设定项列表必须完整,即数组中的每个元素都必须有一个初始值设定项。
考虑定义了两个构造函数的Point类:
//initializing_arrays1.cpp classPoint { public: Point()//Defaultconstructor. { } Point(int,int)//Constructfromtwoints { } }; //AnarrayofPointobjectscanbedeclaredasfollows: PointaPoint[3]={ Point(3,3)//Useint,intconstructor. }; intmain() { }
aPoint的第一个元素是使用构造函数Point(int,int)构造的;剩余的两个元素是使用默认构造函数构造的。
静态成员数组(是否为const)可在其定义中进行初始化(类声明的外部)。例如:
//initializing_arrays2.cpp classWindowColors { public: staticconstchar*rgszWindowPartList[7]; }; constchar*WindowColors::rgszWindowPartList[7]={ "ActiveTitleBar","InactiveTitleBar","TitleBarText", "MenuBar","MenuBarText","WindowBackground","Frame"}; intmain() { }
表达式中的数组
当数组类型的标识符出现在sizeof、address-of(&)或引用的初始化以外的表达式中时,该标识符将转换为指向第一个数组元素的指针。例如:
charszError1[]="Error:Diskdrivenotready."; char*psz=szError1;
指针psz指向数组szError1的第一个元素。请注意,与指针不同,数组不是可修改的左值。因此,以下赋值是非法的:
szError1=psz;