[C++] 纯文本查看 复制代码
#include <iostream>
#include <new>
#include <cstdlib>
using namespace std;
class three_d {
int x, y, z; //三维坐标
public:
three_d() {
x = y = z = 0;
cout << "Constructing 0, 0, 0\n";
}
three_d(int i, int j, int k) {
x = i; y = j; z = k;
cout << "Constructing " << i << ", ";
cout << j << ", " << k;
cout << '\n';
}
~three_d() { cout << "Destructing\n"; }
void *operator new(size_t size);
void *operator new[](size_t size);
void operator delete(void *p);
void operator delete[](void *p);
void show();
};
//重载tree_d的运算符new
void *three_d::operator new(size_t size)
{
void *p;
cout << "Allocating three_d object.\n";
p = malloc(size);
//在内存分配失败时抛出异常
if(!p) {
bad_alloc ba;
throw ba;
}
return p;
}
//重载 three_d 数组的运算符new
void *three_d::operator new[](size_t size)
{
void *p;
cout << "Allocating array of three_d objects.\n";
//在内存分配失败时抛出异常
p = malloc(size);
if (!p) {
bad_alloc ba;
throw ba;
}
return p;
}
//重载 three_d 的运算符delete
void three_d::operator delete(void *p)
{
cout << "Deleting three_d object.\n";
free(p);
}
//重载 three_d 数组的运算符delete
void three_d::operator delete[](void *p)
{
cout << "Deleting array of three_d objects.\n";
free(p);
}
//输出x,x,z的坐标值
void three_d::show()
{
cout << x << " ";
cout << y << " ";
cout << z << endl;
}
int main()
{
three_d *p1, *p2;
try {
p1 = new three_d[3]; //为对象数组分配内存
p2 = new three_d(5, 6, 7); //为单个对象分配内存
}
catch (bad_alloc ba) {
cout << "Allocation error.\n";
return 1;
}
p1[1].show();
p2->show();
delete [] p1; //删除数组
delete p2; //删除对象
return 0;
}