C++的一些问题
我想问一下,如果用new运算符初始化一个对象,delete放在什么地方好呢?
//重载运算符new与delete
#include<iostream.h>
#include<malloc.h>
class Rect
{
int length,width;
public:
Rect(int l,int w)
{
length=l;width=w;
}
void disp()
{
cout<<"面积"<<length*width<<endl;
}
void *operator new(size_t size)//重载new运算符成员函数
{
cout<<"重载new运算符分配内存"<<endl;
return malloc(size);
}
void operator delete(void *p)//重载delete运算符成员函数
{
free(p);
cout<<"重载delete运算符释放内存"<<endl;
}
};
void main()
{
Rect *p;
p=new Rect(5,9);
p->disp ();
delete p;
}
看到没,用完之后释放地
#include<iostream.h>
#include<malloc.h>
class Rect
{
int length,width;
public:
Rect(int l,int w)
{
length=l;width=w;
}
void disp()
{
cout<<"面积"<<length*width<<endl;
}
void *operator new(size_t size)//重载new运算符成员函数
{
cout<<"重载new运算符分配内存"<<endl;
return malloc(size);
}
void operator delete(void *p)//重载delete运算符成员函数
{
free(p);
cout<<"重载delete运算符释放内存"<<endl;
}
};
void main()
{
Rect *p;
p=new Rect(5,9);
p->disp ();
delete p;
}