介绍
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 <stdio.h>
class Student
{
public:
char name[32];
int age;
};
int main()
{
Student* pStu = new Student();
delete pStu;
pStu = NULL;
return 1;
}
5.申请1024个类对象
#include <stdio.h>
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多个对象不能传参数,要求该类必须有默认构造函数。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对菜鸟教程(cainiaojc.com)的支持。如果你想了解更多相关内容请查看下面相关链接
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#cainiaojc.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。