回顾malloc/free
int* p = (int*)malloc(100*sizeof(int));
for(int i=0;i<100;i++)
{
p[i]=0;
}
malloc仅仅是申请一块指定大小的内存,而不是创建对象
用new/delete创建/销毁对象
int* p = new int;
*p = 100;
delete p;
Object* p = new Object;
//与Object* p = new Object();相同
p->value = 100;
delete p;
int* p = new int[N];//创建N个对象,大小为N的对象数组
delete[] p;
默认构造函数
class Circle
{
public:
Circle(int x,int y,int radius):x(x),y(y),radius(radius)
{
}
private:
int x,y;
int radius;
}
Circle* p = new Circle[12]; //错误!!当创建多个对象时必须使用默认构造函数(无参),而不能使用含参的构造函数