C++之動態內存分配

動態申請內存操作符: new

new 類型名T(初始化參數列表)

功能: 在程序執行期間,申請用於存放T類型對象的內存空間,並依初值列表賦以初值。

結果: 如果成功,則返回T類型的指針,指向新分配的內存;如果失敗,則拋出異常。

釋放內存操作符delete

delete 指針p

功能: 釋放指針p所指向的內存。p必須是new操作的返回值。


動態創建對象舉例

#include <iostream>
using namespace std;

class Point {

public:
	Point() : x(0), y(0) {
	cout<<"Default Constructor called."<<endl;
	}

	Point(int x, int y) : x(x), y(y) {
	cout<< "Constructor called."<<endl;
	}

	~Point() { cout<<"Destructor called."<<endl; }

	int getX() const { return x; }
	int getY() const { return y; }
	void move(int newX, int newY) {
	x = newX;
	y = newY;

	}

private:
	int x, y;
};

int main() {
	cout << "Step one: " << endl;
	Point *ptr1 = new Point;     //調用默認構造函數
	delete ptr1;                 //刪除對象,自動調用析構函數
	cout << "Step two: " << endl;
	ptr1 = new Point(1,2);
	delete ptr1;

	return 0;
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章