#include<iostream> using namespace std; class Iceman { public: int num; int hp; int atk; int sword = 0; int bomb = 0; int arrow = 0; 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-06 10:06:10 浏览: 116
使用include <iostream>时一定要加using namespace std
这段代码有两个问题:
1. 在输出语句中,`red_iceman[Iceman_totalNum]`已经是指向新创建的Iceman对象的指针,因此应该使用`->`而不是`.`来访问`hp`成员变量。正确的输出语句应该是:
```
cout << " red iceman " << " born with strength " << red_iceman[Iceman_totalNum]->hp << "," << Iceman_totalNum << " iceman in red headquarter" << endl;
```
2. 在创建Iceman对象时,构造函数中的`totalNum++`语句应该在其他语句之前执行,否则创建的第一个Iceman对象的编号会是0而不是1。正确的构造函数应该是:
```
Iceman(int n, int h, int a) {
totalNum++;
num = n;
hp = h;
atk = a;
}
```
阅读全文