1.对象的动态创建和释放
#include<iostream>
using namespace std;
void main1301()
{
int *a = (int*)malloc(sizeof(int));
*a = 10;
free(a);
int *p = new int;
*p = 20;
int *p1 = new int(30);//从堆内存分配一块“类型”大小的存储空间,返回首地址
printf("*p3:%d \n", *p1);
cout << "hello.." << endl;
system("pause");
return;
}
//分配数组变量
void main1302()
{
//c语言分配数组
int * p = (int*)malloc(sizeof(int*)* 10);
p[0] = 1;
free(p);
//c++分配数组
int *pArray = new int[10];
pArray[1] = 2;
delete[] pArray;//数组加中括号
}
//分配对象
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;
}
new可以调用对象的构造函数,delete可以调用析构函数