介紹
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多個對象不能傳參數,要求該類必須有默認構造函數。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答