申请内存的方式(1,malloc/free;2,new/delete)
一。malloc/free的方式
// 4个int 的大小
int *p = (int*) malloc(16); for (int i = 0; i < 4; ++i) { p[i] = i; } free(p);
二。C++中,用new/delete 操作符取代malloc/free
int *P = new int(123); //申请并赋值; printf("d%",*p); // 123; delete p; int *p = new int [1024]; //申请1024个int对象; for (int i = 0 ; i < 1024; ++i) p[i] = i + 1; delete [] p;
申请类的内存只用new/delete来做,new 的时候会自动调用相对应的类的构造函数,new对象数组的时候,必须要保证类中有默认的构造函数
class Circle { public: int x; int y; int r; Circle() { this->x = 1; this->y = 1; this->r = 1; printf("1111"); } /* Circle():x(10),y(11) { printf("3333"); }*/ Circle(int x,int y,int r) { this->x = x; this->y = y; this->r = r; printf("2222"); } ~Circle() { printf("4444"); } }; int main() { Circle *p1 = new Circle(); //调用默认构造函数 Circle *p2 = new Circle(1,2,3); //调用带参数的构造函数
delete p1;
delete p2;
return 0; }