C++学习之旅 - 引用

作用: 给变量起别名
语法: 数据类型 &别名 = 原名;

基本用法

int a = 10;
int &b = a;

俩者使用的都是10的内存空间

引用的注意事项

  • 引用必须初始化
  • 引用在初始化后,不可以改变
#include <iostream>

using namespace std;

int main() {
    
    
	int a = 10;
	int b = 20;
	int &c = a;
	c = b; // 相当于把c和a都指向那块b的内存

	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
	cout << "c=" << c << endl;
}

在这里插入图片描述

引用做函数参数

#include <iostream>

using namespace std;

void mySwap03(int& a, int& b) {
    
    
	int tmp = a;
	a = b;
	b = a;
	cout << "swap a=" << a << endl;
	cout << "swap b=" << b << endl;
}

int main() {
    
    
	int a = 10;
	int b = 20;
	mySwap03(a, b);
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
}

在这里插入图片描述

引用做函数的返回值

引用是可以作为函数的返回值存在的

注意: 不要返回局部变量引用

int& test01(){
    
    
  int a = 10;
  return a;   
}
int main(){
    
    
  int &ref=test01();
  cout << "ref = " << ref << endl; //第一次结果正常,因为编译器做了保留
  cout << "ref = " << ref << endl;//第二次结果错误,因为a的内存已经释放
  return 0;
}

函数的调用可以作为左值

int& test02(){
    
    
  static int a = 10; //静态变量,存放在全局区(在程序结束后系统进行释放)
  return a;
}
int main(){
    
    
  int &ref = test02();
  cout << "ref = " << ref << endl; //ref是a的别名
  cout << "ref = " << ref << endl;
  test02() = 1000; //函数的调用以在等号的左边出现,操作的是a
  cout << "ref = " << ref << endl;
  cout << "ref = " << ref << endl;
  return 0;
}

在这里插入图片描述

引用的本质

引用的本质就是一个指针常量
引用一旦初始化后就不可以发生改变

常量引用

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

//加上const之后 编译器代码修改 int temp = 10;const int &ref=temp;
const int &ref=10;//引用必须是一块合法的内存空间
//ref = 20; //加入const后变为只读,不可修改
#include <iostream>

using namespace std;

void showValue(int& val) {
    
    
    val = 1000;
	cout << "val=" << val << endl;
}

int main() {
    
    
	int a = 100; //这块a也会改变,指向1000
	showValue(a);
}

为了防止这种误操作

#include <iostream>

using namespace std;

void showValue(const int& val) {
    
    
	cout << "val=" << val << endl;
}

int main() {
    
    
	int a = 100;
	showValue(a);
	cout << a << endl;
}

猜你喜欢

转载自blog.csdn.net/yasinawolaopo/article/details/131051810