引用的本质是指针常量
1.引用基础#include#include using namespace std; int main() { int a =10; int c = 15; int &b = a;//引用必须初始化 //int &b = c;// “b”: 重定义;多次初始化,引用只能初始化依次,不可以更改 cout<<"a = "< 2.引用作为函数参数 #include#include using namespace std; void swapTest(int &a,int &b)//不用指针也可以 { int temp = a; a = b; b = temp; } int main() { int a = 10; int b = 20; swapTest(a,b); cout<<"a : "< 3.引用作为函数返回类型 #include#include using namespace std; //返回值为引用类型 int & test2() { //int a = 29; static int a = 29;//静态变量,存放在全局区,整个程序结束后系统自动释放 return a; } int main() { int &ref = test2();//定义引用类型接收 //自动转换int* const ref = &a cout<<"ref : "< 4.常量引用 #include#include using namespace std; //利用 const 修饰引用,保证输入不改变 void test(const int & a) { //a = 10;//error C3892: “a”: 不能给常量赋值 cout<<"a : "< int a = 20; test(a); return 0; } const修饰引用其他作用
#include#include using namespace std; int main() { int &ref = 10;//error C2440: “初始化”: 无法从“int”转换为“int &” //const int &ref = 10; 加上const修饰可以,编译器自动优化代码,int temp = 10; int &ref = temp; cout<



