介紹
1.malloc,free和new,delete區(qū)別。
2.使用new遵循原則:
使用
1.申請一個對象
int* p1 = new int; delete p1; p1 = NULL;
2.申請多個對象
int* p1 = new int[12]; delete[] p1; p1 = NULL;
3.申請一個長度為1024的char數(shù)組
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多個對象不能傳參數(shù),要求該類必須有默認構(gòu)造函數(shù)。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VEVB武林網(wǎng)的支持。
新聞熱點
疑難解答