10.重载示例(上)

#include <iostream>
#include <stdlib.h>

using namespace std;

class Foo {
public:
	int _id;
	long _data;
	string _str;
public:
	Foo():_id(0) {
		cout << "default ctor. this=" << this << " id=" << _id << endl; 
	}
	Foo(int i):_id(i) {
		cout << "ctor. this=" << this << " id=" << _id << endl; 
	}
	//non virtual 
	~Foo() {
		cout << "dtor. this=" << this << " id=" << _id << endl;
	}
	static void* operator new(size_t size);
	static void operator delete(void* pdead, size_t size);
	static void* operator new[](size_t size);
	static void operator delete[](void* pdead, size_t size);
};
void* Foo::operator new(size_t size){
	Foo* p = (Foo*)malloc(size);
	cout << "Foo::operator new(), size= " << size << endl;
	return p;
}
void Foo::operator delete(void* pdead, size_t size){
	cout << "Foo::operator delete(), pdead= " << pdead << " size= " << size << endl;
	free(pdead);
}
void* Foo::operator new[](size_t size){
	Foo* p = (Foo*)malloc(size);
	cout << "Foo::operator new[](), size= " << size << endl;
	return p;
}
void Foo::operator delete[](void* pdead, size_t size){
	cout << "Foo::operator delete[](), pdead= " << pdead << " size= " << size << endl;
	free(pdead);
}


int main() {
	cout << "sizeof(string) " << sizeof(string) << endl;
	cout << "sizeof(Foo) " << sizeof(Foo) << endl;
	
	Foo* p = new Foo(7);
	delete p;

	cout << endl;
	Foo* pArray = new Foo[5];
	delete []pArray;
	
	cout << "---------------------------------------------------" << endl;
	
	p = ::new Foo(7);
	::delete p;

	cout << endl;
    	pArray = ::new Foo[5];
	::delete []pArray;
	return 0;
}


    Foo* p = new Foo(7);

   delete p;

    Foo* pArray = new Foo[5];

   delete []pArray;   若无members 就调用 globals

    p = ::new Foo(7);

    ::delete p;
    pArray = ::new Foo[5];
    ::delete []pArray; 这样调用(也就是写上global scope operator::会逃过前面所有overloaded functions强迫使用global version)

   都没有进入重载的operator new(),operator delete(),operator new[](),operato[]()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值