#include<iostream>
using namespace std;
//1. new delete/ malloc free
//基础类型 数组 分配类对象
void main301()
{
// int *a=(int*)malloc(sizeof(int));
//*p = 10;
//free(p)
int* p2 = new int;//分配基础类型
*p2 = 20;
free(p2);
//怎么初始化
int* p3 = new int(30);
cout << "*p3:" << *p3 << endl;
delete p3;
return;
}
//分配数组
void main302()
{
//c
int* p = (int*)malloc(sizeof(int)*10);//int array[10
p[0] = 1;
free(p);
//c++
int* pArray = new int[10];//char buf 【25】
pArray[1] = 2;
delete[] pArray;//数组不要吧【】忘记
return;
}
//分配对象 new delete
//相同和不同的抵港 new能执行类型构造函数 delete能执行类的析构函数
class Test
{
public:
Test(int _a)
{
a = _a;
cout << "构造函数执行" << endl;
}
~Test()
{
cout << "析构函数执行" << endl;
}
protected:
private:
int a;
};
void main()
{
//c
Test* pT1 = (Test*)malloc(sizeof(Test));
free(pT1);
//c++
Test* pT2 = new Test(10);
delete pT2;
return;
}
【无标题】
最新推荐文章于 2024-09-13 16:27:15 发布