【C++PrimerPlus】第4章复合类型,string类字符串,getline(),get(),结构体,共用体,枚举。

目录

4.1数组

 4.1.2数组初始化规则 

 4.1.3 C++11数组初始化方法


4.1数组

数组声明指出以下三点:

  1. 存储在每个元素中的值的类型;
  2. 数组名;
  3. 数组中的元素数;
 //typeName arrayName[arraySize];
short months[12];

数组的一些属性,包括声明数组,给数组元素复制以及初始化数组。

#if 1
#include<iostream>
int main()
{
	using namespace std;
	//case 1
	int yams[3];
	yams[0] = 7;
	yams[1] = 8;
	yams[2] = 9;
	//case 2
	int yamcosts[3] = { 20,30,5 };

	//运算
	cout << yams[0] + yams[1] + yams[2] << endl;
	int total = yams[0] * yamcosts[0] + yams[1] * yamcosts[1] + yams[2] * yamcosts[2];
	cout << "The total is" << total << "$\n";
	cout << sizeof yams<<endl;
	cout << sizeof yams[0];
	return 0;
}
#endif

4.1.2数组初始化规则 

只有在定义数组才能使用初始化,以后就不能使用了,也不能将一个数组赋给另一个数组。

int cards[4] = { 3,6,8,10 };//okay
int hand[4];//okay
hand[4] = { 5,6,7,8 };//not allowed
hand = cards;//not allowed

1.初始化数组的时候,提供的值可以少于数组的元素数组。

float hotelTips[5]={5.0,2.5}

2.全部初始化0

long totals[500]={0};

3.不严谨的初始化

short thing[]={1,5,3,8};

 4.1.3 C++11数组初始化方法

1.初始化数组,可以省略等号(=)

double earning[4] {1.2e4,1.6e4,1.3e4,1.7e4};//okay with C++11

2.大括号中可以不包含任何东西,所有元素设置为0

usigned int counts[10]={};//all elements set to 0
float balances[100] {};//all elements set to 0

3.初始化禁止缩窄转换

long a[]={25,92,3.0};//浮点型转换成整型是缩窄操作
char b[]={'h','i',1122011,'\0'};1122011超出char变量取值范围
char c[]={'h','i',112,'\0'};//allowed

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值