<敲了半天,没提交上,郁闷,不重写了>
示例程序:
(1)new
#include <stdafx.h>
#include <malloc.h>
#include <iostream>
using namespace std;
class com
{
public:
int real, image;
com(int x, int y)
{
this->real = x;
this->image = y;
}
};
void main()
{
com c(2, 3);
com *p, *q;
//在堆中分配空间
p = new com(2, 4);
//这两种方式都能动态创建一个对象
//但是下面的语句内存没有初始化
q = (com *)malloc(sizeof(com));
q->real = 2;
q->image = 4;
cout << "hehe" << endl;
//error C2512: 'com' : no appropriate default constructor available
new com[3];
}
(2)重载new delete
示例:在静态区申请动态对象
#include <stdafx.h>
#include <iostream>
using namespace std;
#define N 3
class Item
{
int info, mark;
public:
static Item static_Zone[N];
Item()
{
cout << this << endl;
mark = 0;
}
Item(int x)
{
this->info = x;
this->mark = 1;
}
~Item()
{
cout << "deconstructor is called!" << endl;
this->mark = 0;
}
void * operator new(size_t size) throw (int)
{
cout << "my new" << endl;
for(int i = 0; i < N; i++)
{
if(static_Zone[i].mark == 0)
{
cout << &static_Zone[i] << endl;
return &static_Zone[i];
}
}
throw 1;
}
void operator delete(void *p)
{
cout << "my delete" << endl;
if(p == NULL)
return ;
((Item *)p)->mark = 0;
}
};
Item Item::static_Zone[N];
void functiona()
{
Item *p, *q, *r, *s;
try
{
p = new Item(3);
q = new Item(4);
r = new Item(5);
s = new Item(6);
}catch(int)
{
cout << "memory leak!" << endl;
delete p;
s = new Item(6);
}
}
(3)析构函数和delete的区别
析构函数负责释放由构造函数申请的内存.
delete负责释放new动态申请的内存.