C++构造函数,析构函数

来源:百度知道 编辑:UC知道 时间:2024/05/21 01:48:28
创建一个class Counted,包含一个int类型的成员变量id和一个static int类型的成员变量count。默认构造函数的开头为“Counted() : id(count ++) {”。要求:
a) 构造函数输出id值并且输出“it’s being created”;
b) 析构函数也输出id值并且输出“it is being destroyed”;
c) 使用new创建一个class Counted的对象,并且用delete销毁它;
d) 使用new创建一个class Counted的对象数组,并且用delete[]销毁它;
e) 想办法将内存耗尽,使得在使用new运算符时无法分配内存,并输出提示信息“Out of memory”。

#include <stdio.h>

class Counted
{
private:
int id;
static int count;
public:
// (a)
Counted() : id(count ++) {
printf("ID: %d\t", id);
printf("it's being created\n");
}
// (b)
~Counted() {
printf("ID: %d\t", id);
printf("it is being destroyed\n");
}
};

int Counted::count = 0;

int main()
{
// (c)
Counted *p = NULL;
p = new Counted;
delete p;

// (d)
p = new Counted[10];
delete []p;

// (e)
while (1)
{
p = new Counted;
if (NULL == p)
{
printf("Out of memory\n");
break;
}
}

return 0;
}

内存耗尽,我还没试过,阁下不妨一直死循环new对象