引用变量是一个别名,也就是说,它是某个已存在变量的另外一个名字。一旦把引用初始化为某个变量,就可使用该引用名称或变量名称来指向变量。ios
引用引入了对象的一个同义词。定义引用的表示方法与定义指针类似,只是用&代替了*。引用(reference)是c++对c语言的重要扩充。引用就是某c++
一变量(目标)的一个别名,对引用的操做与对变量直接操做彻底同样。其格式为:类型 &引用变量名 = 已定义过的变量名。函数
引用的特色:spa
①一个变量可取多个别名。指针
②引用必须初始化,只有别名是不能成立的。code
③引用只能在初始化的时候引用一次 ,不能更改成转而引用其余变量。对象
引用很容易与指针混淆,它们之间有三个主要的不一样: blog
#include <iostream> #include <stdio.h> using namespace std; int main(void) { int a=10; int &b=a; // 给a起一个别名b b=20; // 对b操做和对a操做效果是同样的 cout << a <<endl; a=30; cout << b << endl; system("pause"); return 0; }
运行结果:20 30内存
#include <iostream> #include <stdio.h> using namespace std; typedef struct // 定义一个结构体 { int x; int y; }Coord; // 结构体的名字 int main(void) { Coord c; Coord &c1 = c; // 给c起一个别名c1 c1.x = 10; // 对c1操做至关于对c操做 c1.y = 20; cout << c.x << "," << c.y << endl; system("pause"); return 0; }
运行结果:it
格式:类型 *&指针引用名 = 指针简而言之:给地址起一个别名
#include <iostream> #include <stdio.h> using namespace std; int main(void) { int a = 3; int *p = &a; int *&q = p; cout << p << endl; // P = 0093FC60 cout << &q << endl; // &q = 0093FC54 cout << *&q << endl;//*&q = 0093FC60 *q = 5; cout << a << endl; system("pause"); return 0; }
运行结果:
之前咱们在C语言中交换a,b的位置时:
void fun(int *a,int *b) { int c; c = *a; *a = *b; *b = c; }
调用的时候咱们须要吧参数的地址传进去:
int x =10,y = 20; fun(&x,&y);
而当咱们引入了引用,事情就方便多了
void fun(int &a,int &b) // 形参就是引用别名 { int c = 0; c = a; a = b; // a和b都是以别名形式进行交换 b = c; }
调用传参
int x =10,y = 20; fun(x,y);
#include <iostream> #include <stdio.h> using namespace std; void fun(int &a,int &b) int main(void) { int x =10; int y =20; cout << x << "," << y << endl; fun(x,y); cout << x << "," << y << endl; system("pause"); return 0; } void fun(int &a,int &b) { int c = 0; c = a; a = b; b = c; }
输出结果: