第四章 复合类型
C++ Primer Plus自学笔记, 可能不适用于所有人, 仅供参考
4.1 数组
1. 创建数组
例: 创建一个名为months的数组,该数组有 12 个元素,每个元素存储一个short类型的值:
short months[12];
months的类型不是"数组", 而是"short数组".- 强调了数组是使用
short类型创建的.
若将一个值赋给不存在的元素months[101], 编译器不会报错, 但程序运行后可能引发一些严重问题.
- 必须确保程序只使用有效下标值, 避免数组越界.
// arrayone.cpp
#include <iostream>
int main() {
using namespace std;
int yams[3]; //创建有3个元素的int型数组
yams[0] = 7;
yams[1] = 8;
yams[2] = 6;
int yamcosts[3] = {
20, 30, 5}; // 创建初始化数组;
// 使用数组元素
cout << "Total yams = ";
cout << yam[0] + yams[1] + yams[2] << endl;
cout << "The package with " << yams[1] << " yams costs ";
cout << yamcosts[1] << " cents per yam.\n";
int total = yams[0] * yamcosts[0] + yams[1] * yamcosts[1];
total = total + yams[2] * yamcosts[2];
cout << "The total yam expenses is " << total << " cents.\n";
// 数组及元素的 size 大小
cout << "\nSize of yams array = " << sizeof yams << " bytes.\n";
cout << "Size of one element = " << sizeof yams[0] << " bytes.\n";
return 0;
}
- 该程序的输出:
Total yams = 21
The package with 8 yams costs 30 cents per yam.
The total yam expense is 410 cents.
Size of yams array = 12 bytes.
Size of one element = 4 bytes.
- 数组的初始化:
int cards[4] = {
3, 6, 8, 10};
int hand[4];
float hotelTips[5] = {
5.0, 2.5}; // 只初始化前两个元素.
long totals[500] = {
0}; // 将所有元素都初始化为 0
short things[] = {
1, 5, 3, 8}; // things 数组将包含 4 个元素.
// C++11 数组初始化方法
double earning[4] {
1.2e4, 1.6e4, 1.1e4, 1.7e4}; // 省略等于号
unsigned int counts[10] = {
}; // 将所有元素初始化为0.
float balances[100] {
}


402

被折叠的 条评论
为什么被折叠?



