重载运算符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;
}

运行结果


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值