国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

詳解C++編程中數(shù)組的基本用法

2020-05-23 14:09:17
字體:
供稿:網(wǎng)友
這篇文章主要介紹了C++編程中數(shù)組的基本用法,包括數(shù)組的初始化等基本知識,需要的朋友可以參考下
 

可以使用數(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;


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 巨野县| 黑水县| 涟源市| 青冈县| 建阳市| 博乐市| 洞口县| 满城县| 达孜县| 建水县| 抚松县| 永济市| 惠水县| 彩票| 保亭| 泽普县| 贵阳市| 化州市| 都昌县| 登封市| 双流县| 上犹县| 广昌县| 曲水县| 望都县| 宿州市| 贵阳市| 轮台县| 呼图壁县| 淅川县| 永靖县| 高邮市| 桑日县| 柳林县| 呼和浩特市| 桦川县| 囊谦县| 南安市| 拜城县| 吉木乃县| 文昌市|