当前位置: 代码迷 >> 综合 >> C++学习历程9:引用
  详细解决方案

C++学习历程9:引用

热度:26   发布时间:2024-01-29 02:56:26.0

1.使用

语法: 数据类型 &别名 = 原名

int main() {int a = 10;int &b = a;cout << "a = " << a << endl;cout << "b = " << b << endl;b = 100;cout << "a = " << a << endl;cout << "b = " << b << endl;system("pause");return 0;
}

2.注意事项

  • 引用必须初始化

  • 引用在初始化后,不可以改变

int main() {int a = 10;int b = 20;//int &c; //错误,引用必须初始化int &c = a; //一旦初始化后,就不可以更改c = b; //这是赋值操作,不是更改引用cout << "a = " << a << endl;cout << "b = " << b << endl;cout << "c = " << c << endl;system("pause");return 0;
}

3.引用作函数形参

//1. 值传递
void mySwap01(int a, int b) {int temp = a;a = b;b = temp;
}//2. 地址传递
void mySwap02(int* a, int* b) {int temp = *a;*a = *b;*b = temp;
}//3. 引用传递
void mySwap03(int& a, int& b) {int temp = a;a = b;b = temp;
}int main() {int a = 10;int b = 20;mySwap01(a, b);cout << "a:" << a << " b:" << b << endl;mySwap02(&a, &b);cout << "a:" << a << " b:" << b << endl;mySwap03(a, b);cout << "a:" << a << " b:" << b << endl;system("pause");return 0;
}

分析:引用和指针同样能够改变实参的数据,但是引用的语法更为简单,实参只需要变量名而不需要取地址操作。

4.引用作函数返回值

//返回局部变量引用  不合法无法执行
int& test01() {int a = 10; //局部变量return a;
}
//返回静态变量引用  全局地址,合法
int& test02() {static int a = 20;return a;
}int main() {int& ref2 = test02();cout << "ref2 = " << ref2 << endl;cout << "ref2 = " << ref2 << endl;test02() = 1000;cout << "ref2 = " << ref2 << endl;cout << "ref2 = " << ref2 << endl;system("pause");return 0;
}

5.引用本质

引用的本质在c++内部实现是一个指针常量.

//发现是引用,转换为 int* const ref = &a;
void func(int& ref){ref = 100; // ref是引用,转换为*ref = 100
}
int main(){int a = 10;  //自动转换为 int* const ref = &a; 指针常量是指针指向不可改,也说明为什么引用不可更改int& ref = a; ref = 20; //内部发现ref是引用,自动帮我们转换为: *ref = 20;cout << "a:" << a << endl;cout << "ref:" << ref << endl;    func(a);return 0;
}

6.常量引用

常量引用主要用来修饰形参,防止误操作

//常量引用使用的场景,通常用来修饰形参
void showValue(const int& v) {//v += 10;  //不可对形参进行写操作cout << v << endl;
}

 

 

  相关解决方案