一、动态空间申请
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
class Box
{
public:
Box()
{
cout << "Box的无参构造" << endl;
}
~Box()
{
cout << "Box的析构函数" << endl;
}
int a;
};
void test01()
{
Box *p= (Box*)malloc(sizeof(Box));
free(p);
}
void test02()
{
int *p2= new int;
*p2= 99;
cout << "*p2= " << *p2 << endl;
delete p2;
}
void test03()
{
Box *p3= new Box;
(*p3).a= 666;
cout << "p3对象中的a= " << (*p3).a << endl;
delete p3;
}
void test04()
{
int *p4= new int[10];
for(int i=0; i<10; i++)
{
p4[i]= i+10;
}
for(int i=0; i<10; i++)
{
cout << p4[i] << " ";
}
cout << endl;
delete []p4;
}
int main()
{
test03();
test04();
return 0;
}
![1-1](https://i-blog.csdnimg.cn/blog_migrate/203f177d3b272623cdddc9c8cab7b9f6.png)
二、动态对象的使用
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
class Box
{
public:
Box()
{
cout << "Box的无参构造" << endl;
}
Box(int h, int w, int len):height(h), width(w), length(len)
{
cout << "Box的有参构造" << endl;
}
~Box()
{
cout << "Box的析构函数" << endl;
}
private:
int height;
int width;
int length;
};
void test()
{
Box *p= new Box(1, 2, 3);
delete p;
cout << "-------------------------" << endl;
Box *p2= new Box[5];
delete []p2;
}
int main()
{
test();
}
![2-1](https://i-blog.csdnimg.cn/blog_migrate/e5fe1aaafda9d657fb36ea6d4fc4be0b.png)