当前位置:网站首页>C ++ 引用与指针总结
C ++ 引用与指针总结
2022-06-25 22:08:00 【smileapples】
1、定义
- 指针是一个变量,只不过这个变量存储的是一个地址,指向内存的一个存储单元;
- 引用跟原来的变量实质上是同一个东西,只不过是原变量的一个别名而已。
int a = 1;
int *p = &a;
上述代码定义了一个变量a,指针变量p的值为变量a的地址;
int a =1;
int &p = b;
上述代码定义了一个整形变量a和这个整形a的引用b,事实上a和b是同一个东西,在内存占有同一个存储。
2、区别
- 引用不可以为空,在定义的时候必须进行初始化,指针可以为空,任何时候都可以进行初始化;
- 指针的值可以为空,引用的值不可以为NULL,并且在定义时必须初始化;指针的值在初始化后可以修改,即指针可以指向其他的存储单元;
- const可以修饰指针,但是不可以修饰引用;
- 可以有多级指针int **p,但是不可以有多级引用;
- sizeof(指针),得到的是指针本身的大小;sizeof(引用),得到的是所指向变量或者对象的大小;
- 指针和引用的自增运算符意义不一样:指针++ 是地址增加,引用++是值增加;
- 如果返回动态内存分配的对象或内存,必须使用指针,引用可能会引起内存泄漏;
- 指针和引用作为函数参数时的区别:
- 使用指针作为函数的参数
#include<iostream>
using namespace std;
void swap_int(int *a,int *b)
{
// 交换a、b两个变量的值
int tmp = *a;
*a = *b;
*b = tmp;
}
void test(int *p)
{
int a=1;
p=&a;
cout<<"test函数中p的地址:"<<p<<" "<<"test函数中p指针指向的值为:"<<*p<<endl<<endl;
}
int main(void)
{
int a=1,b=2;
int *p=NULL;
swap_int(&a,&b);
cout<<a<<" "<<b<<endl<<endl;
cout<<"main函数中p的地址:"<<&p<<endl;
test(p); // 将指针作为参数进行传递时,事实上也是值传递,只不过传递的是地址
if(p==NULL)
cout<<"指针p为NULL"<<endl<<endl;
}
结果为:
- 使用引用作为函数参数
对形参的修改其实是对实参的修改,所以在用引用进行参数传递时,不仅节约时间,而且可以节约空间。
#include<iostream>
#include<stdlib.h>
using namespace std;
void test(int &a)
{
cout<<&a<<" "<<a<<endl;
}
int main(void)
{
int a=1;
cout<<&a<<" "<<a<<endl;
test(a);
}
结果如图:
边栏推荐
- Use Baidu map API to set an overlay (infowindow) in the map to customize the window content
- String object (constant) pool
- 谈一谈生产环境中swoole协程创建数量控制机制
- The InputStream stream has been closed, but the file or folder cannot be deleted, indicating that it is occupied by the JVM
- Solving typeerror: Unicode objects must be encoded before hashing
- Go language escape analysis complete record
- SSL/TLS、对称加密和非对称加密和TLSv1.3
- Spark日志分析
- CXF
- proxy
猜你喜欢
QT Chinese and English use different fonts respectively
社招两年半10个公司28轮面试面经(含字节、拼多多、美团、滴滴......)
第六章 习题(678)【微机原理】【习题】
idea Kotlin版本升级
达梦数据库修改字段信息采坑记
Database - mongodb
权限设计=功能权限+数据权限
Graduation trip | recommended 5-day trip to London
Extraction system apk
Style setting when there is a separator in the qcombobox drop-down menu
随机推荐
Hibernate architecture introduction and environment construction (very detailed)
Jenkins 发布PHP项目代码
B. Box Fitting-CodeCraft-21 and Codeforces Round #711 (Div. 2)
Doris 运维中遇到的问题
产品经理如何把控产品开发的进度
CSDN add on page Jump and off page specified paragraph jump
UE4 learning record 2 adding skeleton, skin and motion animation to characters
String object (constant) pool
第五章 习题(124、678、15、19、22)【微机原理】【习题】
音频基础知识以及PCM转WAV
Unable to start debugging. Unexpected GDB output from command “-environment -cd xxx“ No such file or
Two ways to center block level elements
sqlServer2008中float类型数据与datetime类型数据互转
谈一谈PHP变量或参数的Copy On Write机制
Px4 multi computer simulation (gazebo)
unsigned与signed之大白话
二叉排序树
The package name of the manifest file in the library project and the app project are not the same
Understanding of pseudo classes
Mutual conversion between QT utf8 and Unicode encoding, and the Unicode encoding output format is &xxxxx