#include<iostream> using namespace std; class Iceman { public: int num; int hp; int atk; static int totalNum; Iceman(int n, int h, int a) { num = n; hp = h; atk = a; totalNum++; } }; int Iceman::totalNum = 0; int main() { Iceman* red_iceman[100]; int Iceman_totalNum = 0; int current_hp = 3; red_iceman[Iceman_totalNum] = new Iceman(Iceman::totalNum + 1, current_hp, 0); Iceman_totalNum++; cout << " red iceman " << " born with strength " << red_iceman[Iceman_totalNum]->hp << "," << Iceman_totalNum << " iceman in red headquarter" << endl; }这段代码有什么问题
时间: 2024-01-02 21:05:22 浏览: 22
这段代码存在两个问题:
1. 当访问 `red_iceman[Iceman_totalNum]->hp` 时,`Iceman_totalNum` 的值已经被加 1,导致访问到了一个未初始化的指针,会导致程序崩溃。
2. 在使用 `new` 运算符为 `red_iceman[Iceman_totalNum]` 分配内存时,没有检查是否超出了数组 `red_iceman` 的边界,可能会导致程序崩溃或者出现未定义的行为。
下面是修改后的代码:
```
#include<iostream>
using namespace std;
class Iceman {
public:
int num;
int hp;
int atk;
static int totalNum;
Iceman(int n, int h, int a) {
num = n;
hp = h;
atk = a;
totalNum++;
}
};
int Iceman::totalNum = 0;
int main() {
Iceman* red_iceman[100];
int Iceman_totalNum = 0;
int current_hp = 3;
red_iceman[Iceman_totalNum] = new Iceman(Iceman::totalNum + 1, current_hp, 0);
Iceman_totalNum++;
cout << " red iceman " << " born with strength " << red_iceman[Iceman_totalNum - 1]->hp << "," << Iceman_totalNum << " iceman in red headquarter" << endl;
delete red_iceman[Iceman_totalNum - 1]; // 释放内存
return 0;
}
```
在这个修改后的代码中,我们使用 `Iceman_totalNum - 1` 来访问刚刚新建的 `Iceman` 对象的 `hp` 属性,避免了上面提到的第一个问题。同时,在分配内存前,我们需要先检查 `Iceman_totalNum` 是否超出了数组 `red_iceman` 的边界,避免了第二个问题。最后,为了避免内存泄漏,我们使用 `delete` 运算符释放了分配的内存。