Week07-C++引用


前言

本篇文章主要介绍了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;;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值