从栈中实例化对象,使用完之后系统会自动回收这块内存。
从堆中实例化对象,使用完之后必须将其内存释放掉~
#include <iostream>
#include <stdlib.h>
using namespace std;
class Location
{
public :
int x;
int y;
void printX()
{
cout << x << endl;
}
void printY()
{
cout << y << endl;
}
};
int main(void)
{
//从栈中实例化对象,使用完之后系统会自动回收这块内存。
Location location1;
location1.x = 10;
location1.y = 20;
location1.printX();
location1.printY();
//从堆中实例化对象,使用完之后必须将其内存释放掉~
Location *p = new Location();
if(NULL == p)
{
cout << "申请内存失败"<<endl;
return 1;
}
p->x = 100;
p->y = 200;
p->printX();
p->printY();
delete p;
p = NULL;
//system("pause");
return 0;
}