用new[]的方法一定要提供默认构造函数(否则不能通过编译).
一、构造函数和析构函数
前面的例子已经运用了new和delete来为类对象分配和释放内存。当使用new为类对象分配内存时,编译器首先用new运算符分配内存,然后调用类的构造函数;类似的,当使用delete来释放内存时,编译器会首先调用泪的析构函数,然后再调用delete运算符。
#include iostream.h
class Date
{
int mo,da,yr;
public:
Date() { cout<<Date constructor<<endl; }
~Date() { cout<<Date destructor<<endl; }
}
int main()
{
Date* dt = new Date;
cout<<Process the date<<endl;
delete dt;
return 0;
}
程序定义了一个有构造函数和析构函数的Date类,这两个函数在执行时会显示一条信息。当new运算符初始化指针dt时,执行了构造函数,当delete运算符释放内存时,又执行了析构函数。
程序输出如下:
Date constructor
Process the date
Date destructor
二、堆和类数组
前面提到,类对象数组的每个元素都要调用构造函数和析构函数。下面的例子给出了一个错误的释放类数组所占用的内存的例子。
#include iostream.h
class Date
{
int mo, da, yr;
public: