new的全局重载,类内部重载!

最近,有个童鞋问我,他对下面这种 new的奇怪写法不明白,很怪异,不像平时的用法,

 

其实这个是new的一种用法而已,只是他接触的少,所以迷糊了,看看下面的代码,大家就知道为什么可以这么写了!

#include <iostream>
using namespace std;


void* operator new(size_t size)
{
	cout << "全局new重载		" << size << endl;
	return malloc(size);
}
 

class  A
{
	double d;
public:
	 A(double d1 ): d(d1)
	 {   
		cout <<d<< "构造函数" << endl;
	  }
	 ~A( )  
	 {
		 cout << d << "析构函数" << endl;
	 }
	 void * operator  new(size_t  size )
	{
		 cout << "类new重载方式一" << size << endl;;
		 return  malloc(size);
	}

//----------------------placement new操作符-------------------------------- 
	 void* operator  new(size_t  size , int param1)
	 {
		 cout << "类new重载方式二" << size <<"    "<< param1 << endl;;
		 return  malloc(size);
	 }

	 void* operator  new(size_t  size, int param1,string  param2)
	 {
		 cout << "类new重载方式三" << size << "    " << param1 << "    " << param2 << endl;;
		 return  malloc(size);
	 }
};

 

int  main()
{
	short* pS = new short ; 

	A* pA = new A(0.11);
	delete pA;
	
	A* pA2 = new  (12)  A(0.22)  ; 
	delete pA2;
	
	A* pA3 = new  (12,"hello")  A(0.33);
	delete pA3;


	return 0;
 }

运行效果图,方式二  与   方式三  就是上述的怪异写法

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页