400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

C++中new和delete的介绍

介绍

成都创新互联成立与2013年,先为黎川等服务建站,黎川等地企业,进行企业商务咨询服务。为黎川企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。

1.malloc,free和new,delete区别。

2.使用new遵循原则:

使用

1.申请一个对象

 int* p1 = new int;
 delete p1;
 p1 = NULL;

2.申请多个对象

 int* p1 = new int[12];
 delete[] p1;
 p1 = NULL;

3.申请一个长度为1024的char数组

 char* pArray = new char[1024];
 for (int i=0; i < 1024; i++)
 {
 pArray[i] = i;
 }
 delete[] pArray;
 pArray = NULL;

4.申请一个类对象

#include 
class Student
{
public:
 char name[32];
 int age;
};
int main()
{
 Student* pStu = new Student();
 delete pStu;
 pStu = NULL;
 return 1;
}

5.申请1024个类对象

#include 
class Student
{
public:
 int age;
 Student()
 {
 ...
 }
 ~Student()
 {
 ...
 }
};
int main()
{
 Student* pStu = new Student[1024];
 for (int i=0; i<1024; i++)
 {
 pStu[i].age = i+1;
 }
 delete[] pStu;
 pStu = NULL;
 return 1;
}

new多个对象不能传参数,要求该类必须有默认构造函数。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对创新互联的支持。如果你想了解更多相关内容请查看下面相关链接


当前标题:C++中new和delete的介绍
标题来源:http://www.bluegullmedia.com/article/gspjsc.html

其他资讯

让你的专属顾问为你服务

0.0407s