2012-02-12 62 views
1

我试图在C++中制作一个简单的口袋妖怪文本游戏。 我创建了一个pokemon类,然后在我的pokemain.cpp尝试从charmander输出hp。 当我尝试运行我的pokemonmain.cpp时,它说charmander没有声明。我确定这是一个愚蠢的问题,但我无法找到答案。从课程到.cpp

这是我的代码。

//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; 
} 

回答

3

变量charmander,bulbausarsquirtle正在构造函数中声明。把它们放在你的主体中,它应该工作。

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; 
} 
+0

感谢您的回复。你们都救了我很多研究 – Chuy 2012-02-12 21:58:49

+0

没问题。我建议你研究一下构造函数是什么。我可以告诉你没有完全理解这个概念。你可以从这里开始:http://www.fredosaurus.com/notes-cpp/oop-condestructors/constructors.html – Tiago 2012-02-12 22:06:42

+0

谢谢你的链接,我目前在C++大学里,而且很难理解我的老师,因为她的口音。 – Chuy 2012-02-12 22:16:13

1

charmander是在构造函数为pokemon类,这意味着这是唯一可见的地方声明。您可能想要将这些声明和使用它们的代码移至main

在同一个类的构造函数中声明一个类的实例无论如何都会导致无限循环 - 考虑一下。

+0

感谢您的回复和回答!有效。 – Chuy 2012-02-12 21:58:21

0

你从来没有实例化类本身。创建类时,很可能会将同一类的实例作为递归实例。这就是说,该程序不知道你来自你的声明。为了解决你的错误,请将小精灵的声明移除到程序的主要部分。

int main() 
{ 
    pokemon c; 

    cout << "C has " << c.hp() << endl; 
    return 0; 
} 

将最有可能的工作。

+0

感谢这个例子! – Chuy 2012-02-12 22:03:57