C++中new和delete的介绍

2020-01-06 19:59:10王振洲

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多个对象不能传参数,要求该类必须有默认构造函数。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对ASPKU的支持。


注:相关教程知识阅读请移步到C++教程频道。