重載運算符new和delete

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;
}

運行結果


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章