首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从类到.cpp

从类到.cpp
EN

Stack Overflow用户
提问于 2012-02-13 05:51:13
回答 3查看 120关注 0票数 1

我试图用c++做一个简单的精灵宝可梦文字游戏。我为精灵宝可梦创建了一个类,然后在我的pokemain.cpp中尝试从charmander输出hp。当我尝试运行我的pokemonmain.cpp时,它提示没有声明charmander。我确信这是一个愚蠢的问题,但我找不到答案。

这是我的代码。

代码语言:javascript
复制
//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;
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-02-13 05:53:21

在构造函数中声明了变量charmanderbulbausarsquirtle。把它们放到你的主板上,它就能工作了。

代码语言:javascript
复制
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;
}
票数 3
EN

Stack Overflow用户

发布于 2012-02-13 05:52:40

charmander是在pokemon类的构造函数中声明的,这意味着它是惟一可见的地方。您可能希望将这些声明和使用它们的代码移到main

在构造函数中为同一个类声明一个类的实例将导致无限循环--想想看。

票数 1
EN

Stack Overflow用户

发布于 2012-02-13 05:56:56

您从未实例化过类本身。在创建类时,很可能会有与递归实例相同的类的实例。也就是说,程序不知道你的声明来自哪里。为了修复您的错误,删除pokemon对程序主要部分的声明。

代码语言:javascript
复制
int main()
{
    pokemon c;

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

很可能会起作用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9253048

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档