前言
本篇文章主要介绍了C++的引用
1. 引用的概念
引用就是给某个变量起一个别名,对引用的操作与对变量直接操作完全一样。
引用的声明方法:类型标识符 &引用名=目标变量名;
补充:
1)一个变量可以定义多个引用
2)引用实际上等价于const类型指针
3)引用跟const一样,是不能改变指向的(只能在定义时初始化)
#include<stdio.h>
#include<stdlib.h>
#include <iostream>
using namespace std;
void swap1(int *const a, int *const b);
void swap2(int &, int &);
int main(void) {
int a = 1;
int &d = a;
int b = 2;
int c = 3;
int &e = a;
int *const p_a = &a;
int *const p_b = &b;
printf("&a:%p\n&b:%p\n&c:%p\n", &a, &b, &c);
printf("sizeof(p_a):%d\nsizeof(d):%d\n", sizeof(p_a), sizeof(d));
printf("swap前的d:%d\n", d);
//swap1(p_a, p_b);
swap2(a, b);
printf("swap后的a:%d\nswap后的b:%d\n", a, b);
printf("swap后的d:%d\n", d);
system("pause");
return 0;
}
void swap1(int *const a, int *const b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
void swap2(int &a, int &b) {//通过别名修改实参
int tmp = a;
a = b;
b = tmp;
}
2.指针的引用
#include <stdio.h>
#include <stdlib.h>
void boy_home1(int **meipo);
void boy_home2(int *&meipo);
int main0120(void) {
int a = 1;
int* p = &a;
int* &p1 = p;//定义指针变量的引用
printf("*p1:%d,&p1:%p\n", *p, &p);
int *meipo;
//boy_home1(&meipo);
boy_home2(meipo);
printf("%d", *meipo);
system("pause");
return 0;
}
void boy_home1(int **meipo1) {
static int money = 10000000;
*meipo1 = &money;
}
void boy_home2(int *&meipo2) {
static int money = 99999999;
meipo2 = &money;
}
3.常引用
常引用声明方式:const 类型标识符 &引用名 = 目标变量名;
用这种方式声明的引用,不能通过引用对目标变量的值进行修改
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a = 10;
const int &b = a;//常引用:不能通过引用修改变量的值
a = 100;
//b = 100;
printf("%d\n", b);
const int &c = 100;//这里相当于定义一个常量
system("pause");
return 0;;
}