简体   繁体   English

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

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

Im completely new to C++ and im trying to make a very simple text based combat system, but I keep getting the error: "objPlayer was not declared in this scope".我对 C++ 完全陌生,我试图制作一个非常简单的基于文本的战斗系统,但我不断收到错误消息:“objPlayer 未在此范围内声明”。

All the code is written before the main() function:所有代码都写在 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;
    }

You don't have to create a variable inside a class pointing to the object of that class you are using.您不必在指向您正在使用的类的对象的类中创建变量。 It is already declared and is called this .它已经被声明并被称为this

With operator -> you can then access member variables from this .使用 operator ->然后您可以从this访问成员变量。 Like so:像这样:

#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();
}

As you can see, I am using something called constructor to create new instance of Player.如您所见,我正在使用称为constructor东西来创建 Player 的新实例。 It is just function without return type, declared with the same name as the class.它只是没有返回类型的函数,声明为与类同名。 It initializes member variable starting data and you can pass some values to it too.它初始化成员变量起始数据,您也可以将一些值传递给它。

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

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