/**
* cppTest-7.6:重载new&delete
*
*1、在类里面定义的重载new、delete只能对该类起作用
*2、new、delete都是类的静态成员,而且是自动成为静态成员,无需程序员手动声明。
* 所以不能访问类的非静态成员!
*3、new和delete应该成对出现,即都重载或都全局。但是不这样做也不会出错。
*4、new在对象创建之前被调用,delete在对象销毁后调用,即:
* 先new出空间再调用构造函数:
* Class *c=new Class(...);<=>Class *c=Class::operator new (sizeof(Class));Class::Class(c,...);
* 先调用析构函数再delete掉空间:
* Class::~Class(c);Class::operator delete(c,sizeof(Class));
* author 炜sama
*/
#include<iostream.h>
#include<stdlib.h>
class three_d{
private:
int a;
static int si;
public:
int x,y,z;
three_d(int a,int b,int c){x=a;y=b;z=c;}
//必须返回void*。
//size_t是stdlib.h里定义的:typedef unsigned int size_t;,
//下面调用p=new three_d(1,2,3);时自动将size_t初始化为sizeof(three_d)。
//其实size_t替换为unsigned int也没错,但是不能这么做!因为环境不同,size_t的定义可能就不同了!
void *operator new(size_t size)
{
//cout<<a<<endl;//不能访问非静态变量a!delete中也是这样!
cout<<"new时打印静态成员si:"<<si<<endl;
cout<<"类的重载new"<<endl;
return malloc(size);
}
//返回必须是void
//第一个参数是void *
void operator delete(void *p){cout<<"类的重载delete"<<endl;free(p);}
//void operator delete(void *p,size_t size){cout<<"类的重载delete"<<endl;free(p);}
void print(){cout<<x<<","<<y<<","<<z<<endl;}
};
int three_d::si=100;
ostream& operator<<(ostream& stream,three_d obj)
{
stream<<obj.x<<",";
stream<<obj.y<<",";
stream<<obj.z;
return stream;
}
void main()
{
three_d *p,*p1;
p=new three_d(1,2,3);//这里调用的是类的重载new
if(!p){
cout<<"new p失败!"<<endl;
return;
}
cout<<*p<<endl;
p->print();
delete p;//同上
p1=::new three_d(4,5,6);//::是全局域解释操作符,即使类重载了new,一样会调用全局的new!
if(!p1){
cout<<"new p1失败!"<<endl;
return;
}
cout<<*p1<<endl;
p1->print();
::delete p1;//同上
int *pt=new int;//重载new只对操作的类有用,对于普通的类型调用的是全局的new!
if(!pt){
cout<<"new pt失败!"<<endl;
return;
}
*pt=10;
cout<<*pt<<endl;
delete pt;//同上
}
cppTest-7.6:重载new&delete
最新推荐文章于 2013-12-30 14:49:54 发布