详解C++编程中数组的基本用法

2025-05-27 0 46

可以使用数组下标操作符 ([ ]) 访问数组的各个元素。 如果在无下标表达式中使用一维数组,组名计算为指向该数组中的第一个元素的指针。

?

1

2

3

4

5

6

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

}

使用多维数组时,在表达式中使用各种组合。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16
// 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 类:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20
// 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 ) 构造的;剩余的两个元素是使用默认构造函数构造的。
静态成员数组(是否为 const)可在其定义中进行初始化(类声明的外部)。例如:

?

1

2

3

4

5

6

7

8

9

10

11

12

13
// 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()

{

}

表达式中的数组
数组类型的标识符出现在 sizeof、address-of (&) 或引用的初始化以外的表达式中时,该标识符将转换为指向第一个数组元素的指针。 例如:

?

1

2
char szError1[] = "Error: Disk drive not ready.";

char *psz = szError1;

指针 psz 指向数组 szError1 的第一个元素。 请注意,与指针不同,数组不是可修改的左值。 因此,以下赋值是非法的:

?

1
szError1 = psz;

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 详解C++编程中数组的基本用法 https://www.kuaiidc.com/74906.html

相关文章

发表评论
暂无评论