025 、new和delete的基本使用,是c++的操作符

/*
	new和delete的基本使用,是c++的操作符
	
	結論:
		new不但可以分配內存,還可以初始化對象
		malloc不會調用類的構造函數
		free不會調用類的析構函數
	注意:
		如果用一個指針變量pt先後指向不同的動態對象,應注意指針變量
		的當前指向,以免刪錯了對象。在執行delete運算符時,在釋放內存
		空間之前,自動調用析構函數,完成有關善後清理工作。
*/
#if 1
class Test
{
public:
	Test(int _a)
	{
		a = _a;
		cout << "構造函數執行" << endl;
	}
	~Test()
	{
		cout << "析構函數執行" << endl;
	}

protected:
private:
	int a;
};

void test()
{
	int *p = new int;
	*p = 20;
	printf("*p = %d\n", *p);
	delete p;

	int *p1 = new int(21);//定義並初始化
	printf("*p1 = %d\n", *p1);
	delete p1;

	int *pArray = new int[10];
	pArray[0] = 10;
	delete[]pArray;

	char *str = new char[25];
	strcpy(str, "12345");
	printf("str = %s\n", str);
	delete[]str;
	
	cout << "1-使用malloc創建對象,free釋放對象" << endl<<endl;
	//對象的操作
	Test *pT1 = (Test *)malloc(sizeof(Test));
	free(pT1);
	cout << "2-使用new創建對象,delete釋放對象" << endl<< endl;
	Test *pT2 = new Test(10);   //new能執行類型構造函數
	delete(pT2);                //delete操作符 能執行類的析構函數

	printf("---------------------------\n");
	//深入分析  

	//malloc  用delete釋放
	cout << "3-使用malloc創建對象,delete釋放對象" << endl << endl;
	Test *pT3 = (Test *)malloc(sizeof(Test));
	delete(pT3);

	//new 用free釋放
	cout << "4-使用new創建對象,free釋放對象" << endl << endl;
	Test *pT4 = new Test(10);   //new能執行類型構造函數
	free(pT4);                  //delete操作符 能執行類的析構函數
	
}

#endif

在這裏插入圖片描述

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