我是C ++的新手,我正在练习继承,我输入下面的代码。在Squirtle.cpp中,visual studio告诉我newHp,newLevel,newExperience和newAttack都是未定义的。为什么会这样?我如何解决它?我在这里查找了其他示例,例如this,但我猜他们不会收到错误,因为他们的基础和子构造函数都在同一个文件中?
**** **** Pokemon.h
#ifndef _POKEMON_
#define _POKEMON_
#include <string>
#include <iostream>
using namespace std;
class Pokemon {
//Members
private:
int hp;
int level;
int experience;
int attack;
//Member functions
public:
Pokemon(int newHp, int newLevel, int newExperience, int newAttack);
virtual ~Pokemon();
int getHp();
int getAttack();
void setHp(int newHp);
void setAttack(int newAttack);
void physicalAttack(Pokemon &target);
};
#endif
**** **** Pokemon.cpp
#include "Pokemon.h"
Pokemon::Pokemon(int newHp, int newLevel, int newExperience, int newAttack)
{
hp = newHp;
level = newLevel;
experience = newExperience;
attack = newAttack;
}
Pokemon::~Pokemon()
{
}
int Pokemon::getHp()
{
return hp;
}
int Pokemon::getAttack()
{
return attack;
}
void Pokemon::setHp(int newHp)
{
hp = newHp;
}
void Pokemon::setAttack(int newAttack)
{
attack = newAttack;
}
void Pokemon::physicalAttack(Pokemon &target)
{
target.setHp(target.getHp() - getAttack());
cout << "Dealt " << getAttack() << "damages to target! Hp is now at " << target.getHp() << "!";
}
**** **** Squirtle.h
#include "Pokemon.h"
#ifndef _SQUIRTLE_
#define _SQUIRTLE_
class Squirtle :Pokemon{
//members
private:
int mana;
//member functions
public:
Squirtle(int newMana);
int getMana();
void setMana(int newMana);
void freeze(Pokemon &target);
};
#endif
**** **** Squirtle.cpp
#include "Squirtle.h"
Squirtle::Squirtle(int newMana):Pokemon(newHp, newLevel, newExperience, newAttack)
{
mana = newMana;
}
int Squirtle::getMana()
{
return mana;
}
void Squirtle::setMana(int newMana)
{
mana = newMana;
}
void Squirtle::freeze(Pokemon &target)
{
setMana(getMana() - 1);
target.setAttack(0);
cout << "Squirtle has frozen the target! Its attack is now reduced to 0!";
}
答案 0 :(得分:0)
在此构造函数定义中
Squirtle::Squirtle(int newMana):Pokemon(newHp, newLevel, newExperience, newAttack)
{
mana = newMana;
}
标识符newHp,newLevel,newExperience,newAttack未声明。所以编译器不知道例如什么是newHp