我试图用c++做一个简单的精灵宝可梦文字游戏。我为精灵宝可梦创建了一个类,然后在我的pokemain.cpp中尝试从charmander输出hp。当我尝试运行我的pokemonmain.cpp时,它提示没有声明charmander。我确信这是一个愚蠢的问题,但我找不到答案。
这是我的代码。
//class named stats
#include <iostream>
using namespace std;
class pokemon
{
int health, damage;
public:
pokemon (int,int);
int hp()
{
return (health);
}
int dmg()
{
return (damage);
}
};
pokemon::pokemon (int hp, int dmg)
{
health = hp;
damage = dmg;
pokemon charmander (25,3);
pokemon bulbasaur (20,4);
pokemon squirtle (30,2);
cout<<" Charmander has "<<charmander.hp()<<" hp and "<<charmander.dmg()<<" damage.\n";
cout<<" Bulbasaur has "<<bulbasaur.hp()<<" hp and "<<bulbasaur.dmg()<<" damage.\n";
cout<<" Squirtle has "<<squirtle.hp()<<" hp and "<<squirtle.dmg()<<" damage.\n";
}
//pokemain.cpp
#include <iostream>
#include "stats.h"
using namespace std;
int main()
{
cout<<charmander.hp();
return 0;
}发布于 2012-02-13 05:53:21
在构造函数中声明了变量charmander、bulbausar和squirtle。把它们放到你的主板上,它就能工作了。
int main(void) {
pokemon charmander(25,3);
pokemon bulbausar(25,3);
pokemon squirtle(25,3);
cout<<" Charmander has "<<charmander.hp()<<" hp and "<<charmander.dmg()<<" damage.\n";
cout<<" Bulbasaur has "<<bulbasaur.hp()<<" hp and "<<bulbasaur.dmg()<<" damage.\n";
cout<<" Squirtle has "<<squirtle.hp()<<" hp and "<<squirtle.dmg()<<" damage.\n";
return 0;
}发布于 2012-02-13 05:52:40
charmander是在pokemon类的构造函数中声明的,这意味着它是惟一可见的地方。您可能希望将这些声明和使用它们的代码移到main。
在构造函数中为同一个类声明一个类的实例将导致无限循环--想想看。
发布于 2012-02-13 05:56:56
您从未实例化过类本身。在创建类时,很可能会有与递归实例相同的类的实例。也就是说,程序不知道你的声明来自哪里。为了修复您的错误,删除pokemon对程序主要部分的声明。
int main()
{
pokemon c;
cout << "C has " << c.hp() << endl;
return 0;
}很可能会起作用。
https://stackoverflow.com/questions/9253048
复制相似问题