c++学习(第6天)---new操作符和delete操作符
2021/5/20 20:58:27
本文主要是介绍c++学习(第6天)---new操作符和delete操作符,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1.new 操作符
作用:申请内存,利用new创建的数据,会返回该数据对应类型的指针
语法: new 数据类型
接下来利用代码认识new关键字的使用:
1.1 利用new关键字开辟的内存,返回的是开辟内存的地址
#include<iostream> using namespace std; int main() { void new_function();//函数声明 //调用函数 new_function(); system("pause"); return 0; } void new_function() { int *p;//定义int类型的指针p p=new int(10);//利用new关键字开辟一块内存,内存中存放的数据为10,利用指针p接收内存的地址 int q;//定义局部变量q q = (int)p;//将开辟的内存的地址强转为int型,利用q接收 cout << "开辟的内存地址为:" << q << endl; cout << "开辟的内存地址为:" << q << endl; cout << "开辟的内存地址为:" << q << endl; cout << "开辟的内存地址为:" << q << endl; }
运行结果:
1.2 获取开辟内存中初始化的数据
#include<iostream> using namespace std; int main() { int * new_function();//函数声明 int *t = new_function();//定义int类型指针t //调用函数 cout << "内存中存放的数为:" << *t << endl; cout << "内存中存放的数为:" << *t << endl; cout << "内存中存放的数为:" << *t << endl; cout << "内存中存放的数为:" << *t << endl; system("pause"); return 0; } int * new_function() { int *p;//定义int类型的指针p p=new int(10);//利用new关键字开辟一块内存,内存中存放的数据为10,利用指针p接收内存的地址 return p; }
运行结果:
2.delete关键字
作用:释放利用new关键字开辟的内存
语法: detete 指针变量
#include<iostream> using namespace std; int main() { int * new_function();//函数声明 int *t = new_function();//定义int类型指针t //调用函数 cout << "内存中存放的数为:" << *t << endl; cout << "内存中存放的数为:" << *t << endl; cout << "内存中存放的数为:" << *t << endl; cout << "内存中存放的数为:" << *t << endl; delete t; cout << "释放内存以后的数据为:" << *t << endl; system("pause"); return 0; } int * new_function() { int *p;//定义int类型的指针p p=new int(10);//利用new关键字开辟一块内存,内存中存放的数据为10,利用指针p接收内存的地址 return p; }
运行以上代码发现出现了异常。因为我们已经释放了内存空间,再去读取里面的值时,肯定要报错
这篇关于c++学习(第6天)---new操作符和delete操作符的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04el-table 开启定时器下,表格的选中状态会消失是什么原因-icode9专业技术文章分享
- 2024-10-03如何安装和初始化飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03如何安装 App 并连接到飞牛 NAS?-icode9专业技术文章分享
- 2024-10-03如何安装飞牛 TV 并连接到影视服务器?-icode9专业技术文章分享
- 2024-10-03如何在PVE和ESXI上安装飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS安装系统异常情况处理-icode9专业技术文章分享
- 2024-10-03飞牛NAS如何创建存储空间?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS硬盘会自动休眠吗?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何安装飞牛影视和创建媒体库?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何为家人朋友开通影视账号?-icode9专业技术文章分享