目录
4.1数组
数组声明指出以下三点:
- 存储在每个元素中的值的类型;
- 数组名;
- 数组中的元素数;
//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