简体   繁体   中英

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".

All the code is written before the main() function:

#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 .

With operator -> you can then access member variables from 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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