1、在类内重载new和delete,相当于是成员变量(局部重载)
使用new分配新对象的时候,会先调用new重载函数,然后在调用构造函数。调用方式和系统的new的用法是一样的。
头文件
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
class OperatorNew
{
private:
int x,y,z;
public:
OperatorNew(int a,int b,int c);
~OperatorNew()
{
cout << "Destructing\n";
}
void *operator new(size_t size);
void operator delete(void *p);
friend ostream & operator <<(ostream &stream,three_d obj);
};
源文件
OperatorNew::OperatorNew(int a,int b,int c)
{
cout << "Constructing\n";
x = a;
y = b;
z = c;
}
void *OperatorNew::operator new(size_t size)
{
cout << "in threee_d new\n";
return malloc(size);
}
void OperatorNew::operator delete(void *p)
{
cout << "in three_d delete\n" ;
free(p);
}
ostream &operator <<(ostream &os,three_d obj)
{
os << obj.x << ",";
os << obj.y << ",";
os << obj.z << "\n";
return os;
}
int _tmain(int argc, _TCHAR* argv[])
{
OperatorNew*p = new OperatorNew(1,2,3);
OperatorNew*p1 = new OperatorNew(4,5,6);
if(!p || !p1)
{
cout << "Allocation failure" << endl;
return 1;
}
cout << *p << *p1;
delete p;
delete p1;
cout << "Application Run Successfully!" << endl;
return 0;
}
输出结果
2、全局重载new和delete
如果这样的话,系统的new和delete将不会被调用,只调用我们自己重载的new和delete
头文件
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
class OperatorNew
{
private:
int x,y,z;
public:
OperatorNew(int a,int b,int c);
~OperatorNew()
{
cout << "Destructing\n";
}
friend ostream & operator <<(ostream &stream,three_d obj);
};
源文件
OperatorNew::three_d(int a,int b,int c)
{
cout << "Constructing\n";
x = a;
y = b;
z = c;
}
void *operator new(size_t size)
{
cout << "in threee_d new\n";
return malloc(size);
}
void operator delete(void *p)
{
cout << "in three_d delete\n" ;
free(p);
}
ostream &operator <<(ostream &os,three_d obj)
{
os << obj.x << ",";
os << obj.y << ",";
os << obj.z << "\n";
return os;
}
int _tmain(int argc, _TCHAR* argv[])
{
OperatorNew*p = new OperatorNew(1,2,3);
OperatorNew*p1 = new OperatorNew(4,5,6);
if(!p || !p1)
{
cout << "Allocation failure" << endl;
return 1;
}
cout << *p << *p1;
delete p;
delete p1;
cout << "Application Run Successfully!" << endl;
return 0;
}
运行结果