示例:
class Obj
{
public:
Obj() { cout << "Initialization" << endl; }
~Obj() { cout << "Destroy" << endl; }
void Initialize() { cout << "Initialization" << endl; }
void Destroy() { cout << "Destroy" << endl; }
};
void UseMallocFree()
{
Obj *a = (Obj*)malloc(sizeof(obj));
a->Intialize();
// ...
a->Destroy();
free(a);
}
void UseNewDelete()
{
Obj *a = new Obj;
//...
delete a;
}
类Obj 的函数Initialize模拟了构造函数的功能,函数Destroy模拟了析构函数的功能。函数UseMallocFree中,由于malloc/free不能执行构造函数与析构函数,必须调用成员函数Initialize和Destroy来完成初始化与清除工作。函数UseNewDelete则简单得多。
这只是个例子,不会有人用malloc/free来创建类对象。另外,new和delete配套使用,new[]和delete[]配套使用。