繁体   English   中英

C++ 错误:未在此范围内声明类/对象

[英]C++ Error: class/object was not declared in this scope

我对 C++ 完全陌生,我试图制作一个非常简单的基于文本的战斗系统,但我不断收到错误消息:“objPlayer 未在此范围内声明”。

所有代码都写在 main() 函数之前:

#include <iostream>

using namespace std;


    //DECLARE THE UNIT CLASS
    class generalUnit {
    public:
    int health; //the amount of health the unit has
    };


    //DECLARE THE PLAYER THOUGH THE UNIT CLASS 
    void generatePlayer() {
    generalUnit objPlayer;
    int objPlayer.health = 100;
    }


    //DECLARE AND INITIALIZE ALL COMMANDS
    //CHECK STATS
    void comCheckStats() {
        cout << objPlayer.health << endl;
    }

您不必在指向您正在使用的类的对象的类中创建变量。 它已经被声明并被称为this

使用 operator ->然后您可以从this访问成员变量。 像这样:

#include <iostream>
#include <string>

using namespace std;

class Player
{
public:
    int health;

    // this is constructor
    Player(int health_at_start)
    {
        this->health = health_at_start;
    }

    void comCheckStats()
    {
        cout << this->health << '\n';
    }
};

int main()
{
    // create player with 100 health
    Player p1(100);
    p1.comCheckStats();

    // create player with 200 health
    Player p2(200);
    p2.comCheckStats();
}

如您所见,我正在使用称为constructor东西来创建 Player 的新实例。 它只是没有返回类型的函数,声明为与类同名。 它初始化成员变量起始数据,您也可以将一些值传递给它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM