動態申請內存操做符 new
-
new 類型名T(初始化參數列表)c++
-
功能:在程序執行期間,申請用於存放T類型對象的內存空間,並依初值列表賦以初值。數組
-
結果值:成功:T類型的指針,指向新分配的內存;失敗:拋出異常。函數
釋放內存操做符delete
-
delete 指針pspa
-
功能:釋放指針p所指向的內存。p必須是new操做的返回值。指針
1 //例1 動態建立對象舉例 2 3 #include <iostream> 4 5 using namespace std; 6 7 class Point { 8 9 public: 10 11 Point() : x(0), y(0) { 12 13 cout<<"Default Constructor called."<<endl; 14 15 } 16 17 Point(int x, int y) : x(x), y(y) { 18 19 cout<< "Constructor called."<<endl; 20 21 } 22 23 ~Point() { cout<<"Destructor called."<<endl; } 24 25 int getX() const { return x; } 26 27 int getY() const { return y; } 28 29 void move(int newX, int newY) { 30 31 x = newX; 32 33 y = newY; 34 35 } 36 37 private: 38 39 int x, y; 40 41 }; 42 43 int main() { 44 45 cout << "Step one: " << endl; 46 47 Point *ptr1 = new Point; //調用默認構造函數 48 49 delete ptr1; //刪除對象,自動調用析構函數 50 51 cout << "Step two: " << endl; 52 53 ptr1 = new Point(1,2); 54 55 delete ptr1; 56 57 return 0; 58 59 }
1 運行結果: 2 3 Step One: 4 5 Default Constructor called. 6 7 Destructor called. 8 9 Step Two: 10 11 Constructor called. 12 13 Destructor called.
分配和釋放動態數組
-
分配:new 類型名T [ 數組長度 ]code
-
數組長度能夠是任何表達式,在運行時計算對象
-
-
釋放:delete[] 數組名pblog
-
釋放指針p所指向的數組。
p必須是用new分配獲得的數組首地址。圖片
1 //例2 動態建立對象數組舉例 2 3 #include<iostream> 4 5 using namespace std; 6 7 class Point { //類的聲明同例6-16,略 }; 8 9 int main() { 10 11 Point *ptr = new Point[2]; //建立對象數組 12 13 ptr[0].move(5, 10); //經過指針訪問數組元素的成員 14 15 ptr[1].move(15, 20); //經過指針訪問數組元素的成員 16 17 cout << "Deleting..." << endl; 18 19 delete[] ptr; //刪除整個對象數組 20 21 return 0; 22 23 }
1 運行結果: 2 3 Default Constructor called. 4 5 Default Constructor called. 6 7 Deleting... 8 9 Destructor called. 10 11 Destructor called.
動態建立多維數組
new 類型名T[第1維長度][第2維長度]…;
-
若是內存申請成功,new運算返回一個指向新分配內存首地址的指針。
例如:
char (*fp)[3];
fp = new char[2][3];
1 //例3 動態建立多維數組 2 3 #include <iostream> 4 5 using namespace std; 6 7 int main() { 8 9 int (*cp)[9][8] = new int[7][9][8]; 10 11 for (int i = 0; i < 7; i++) 12 13 for (int j = 0; j < 9; j++) 14 15 for (int k = 0; k < 8; k++) 16 17 *(*(*(cp + i) + j) + k) =(i * 100 + j * 10 + k); 18 19 for (int i = 0; i < 7; i++) { 20 21 for (int j = 0; j < 9; j++) { 22 23 for (int k = 0; k < 8; k++) 24 25 cout << cp[i][j][k] << " "; 26 27 cout << endl; 28 29 } 30 31 cout << endl; 32 33 } 34 35 delete[] cp; 36 37 return 0; 38 39 }