定义了一个Iceman类, int Iceman_totalNum=1; Iceman* red_iceman[100]; red_iceman[Iceman_totalNum] = new Iceman(); cout << t << " red iceman " << " born with strength " << red_iceman[Iceman_totalNum]->hp << "," << Iceman_totalNum << " iceman in red headquarter" << endl;有什么问题
时间: 2024-01-21 11:19:31 浏览: 71
一个通用的JavaScript分页
这段代码定义了一个Iceman类,并且创建了一个名为red_iceman的指针数组,数组大小为100。同时,代码通过new运算符为red_iceman数组中的第Iceman_totalNum个元素分配了内存空间,创建了一个新的Iceman对象。
问题可能出现在下面这行代码中:
```
cout << t << " red iceman " << " born with strength " << red_iceman[Iceman_totalNum]->hp << "," << Iceman_totalNum << " iceman in red headquarter" << endl;
```
在这行代码中,程序访问了red_iceman数组中的第Iceman_totalNum个元素的hp属性。但是,在这个时候,Iceman_totalNum的值为1,而red_iceman数组中只有一个元素,因此访问red_iceman[1]会导致数组越界错误。应该将Iceman_totalNum的初始值设置为0,或者在创建新的Iceman对象之前将Iceman_totalNum的值加1。
阅读全文