#include<iostream> usingnamespacestd; intmain(){ int a = 10; int& b = a; cout << "a = " << a << endl; cout << "b = " << b << endl;
cout << "通过引用修改后:" << endl; cout << "a = " << a << endl; cout << "b = " << b << endl; return0; }
运行结果:
1 2 3 4 5
a = 10 b = 10 通过引用修改后: a = 10 b = 10
2. 引用注意事项
引用必须初始化
引用在初始化后,不可以修改
1 2 3 4 5 6 7 8 9 10 11 12 13
#include<iostream> usingnamespacestd; intmain(){ //int& b;//报错,引用必须初始化 int a = 10; int b = 10; int& c = a; c = b;//这是赋值操作,而不是更改引用 cout << "c = " << c << endl; cout << "a = " << a << endl; cout << "b = " << b << endl; return0; }
#include<iostream> usingnamespacestd; //交换函数 //1、值传递 voidSwap01(int a, int b){ int temp = a; a = b; b = temp; } //2、地址传递 voidSwap02(int* a, int* b){ int temp = *a; * a = *b; * b = temp; } //3、引用传递,形参是实参的别名,所以可以将实参数据交换 voidSwap03(int &a, int &b){ int temp = a; a = b; b = temp; }
intmain(){ int a = 10; int b = 20; //值传递 Swap01(a, b); cout << "值传递交换" << endl; cout << "a = " << a << endl; cout << "b = " << b << endl; //地址传递 cout << "\n地址传递交换" << endl; Swap02(&a, &b); cout << "a = " << a << endl; cout << "b = " << b << endl;
//引用传递 Swap03(a, b); cout << "\n引用传递交换" << endl; cout << "a = " << a << endl; cout << "b = " << b << endl;
#include<iostream> usingnamespacestd; intmain(){ int a = 10; int b = 10; constint* p; p = &a; cout << "*p = " << *p << endl; p = &b; cout << "*p = " << *p << endl; //*p = 10;错误,不可以修改常量指针指向的值的内容 a = 20; cout << "*p = " << *p << endl; return0; }
运行结果:
1 2 3
*p = 10 *p = 10 *p = 10
指针常量:const修饰常量
特点:指针本身是常量,不可以修改,但是指针指向的值可以修改。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include<iostream> usingnamespacestd; intmain(){ int a = 10; int b = 20; //int* const pp;//报错,常量需要设定初始值 int* const p = &a; //p = &b;//报错,指针是常量,不可以修改 *p = 20;
#include<iostream> usingnamespacestd; voidSwap(int* a, int* b); intmain(){ int a = 10; int b = 20; cout << "交换前:" << endl; cout << "a = " << a << endl; cout << "b = " << b << endl;
Swap(&a, &b);//地址传递 cout << "交换后:" << endl; cout << "a = " << a << endl; cout << "b = " << b << endl;
return0; } voidSwap(int* a, int* b){ int temp; temp = *a; *a = *b; *b = temp; }