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

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

詳解C++編程中數組的基本用法

2020-01-26 14:44:35
字體:
來源:轉載
供稿:網友

可以使用數組下標操作符 ([ ]) 訪問數組的各個元素。 如果在無下標表達式中使用一維數組,組名計算為指向該數組中的第一個元素的指針。

// 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;

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 扶风县| 墨竹工卡县| 西畴县| 海阳市| 遂宁市| 新绛县| 江津市| 银川市| 栖霞市| 扶绥县| 襄汾县| 永德县| 互助| 潮州市| 阿勒泰市| 松溪县| 句容市| 基隆市| 巴塘县| 平邑县| 华宁县| 尼勒克县| 定边县| 抚顺市| 连州市| 霍城县| 无为县| 清丰县| 辰溪县| 镇远县| 神木县| 虞城县| 新龙县| 莫力| 吴忠市| 铜鼓县| 安多县| 安多县| 凤山市| 微博| 凉城县|