一、数组
PS:VS2019中是不支持数组长度是变量的(部分编译器可行)
数组声明示例:
const int n = 100;
int num[n];
1、数组定义:
int num[] = { 192,12,'k',true };
PS:以上的代码看似混合了很多种类型,好像会报错,但是其实并不会报错,原因是:在C++中字符型和bool型都是用整型表示的。
2、初始化一维数组:
下面是五种一维数组的初始化方式:
int years[6] = { 2012,2013,2014 };
int months[12] = { 1,3,5,7,8,10,12 };
int days[] = { 1,15 };
int mydate[]{ 1,15 };
float what[100]{};
总结一下:
1)未赋值的元素自动补齐初始化为0
2)数组所定义的长度不可以比元素值少
二、函数
1、传递方式
1)值传递
//定义函数,实现两个数字进行交换函数
void swap(int num1, int num2)
{
cout << "交换前:" << endl;
cout << "num1 = " << num1 << endl;
cout << "num2 = " << num2 << endl;
int temp = num1;
num1 = num2;
num2 = temp;
cout << "交换后:" << endl;
cout << "num1 = " << num1 << endl;
cout << "num2 = " << num2 << endl;
}
int main(){
int num1 = 15;
int num2 = 24;
swap(num1, num2);
cout << num1 << " " << num2 << endl;
}
输出结果:
交换后:
num1 = 24
num2 = 15
15 24
PS:当我们做值传递的时候,函数的形参发生改变,并不会影响实参
2)引用传递
void MySwap03(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
cout << "MySwap03 引用传递" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
3)指针传递
void MySwap02(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
cout << "MySwap02 地址传递" << endl;
cout << "a = " << *a << endl;
cout << "b = " << *b << endl;
}