Call function to return a private variable from a class that does not work

So, I am making a small game in C ++, and I ran into a problem. I have a class called a player inside my player.h file, and inside this class I have a public getPotion() function. I also have a static variable called potion . I have the same thing for player health, and the getHealth() function perfectly returns the private static int playerHealth . But apparently there is no reason, the getPotion function getPotion not return the potion. Instead, I get an error message. I also included the header file in all my other files.

Here is the code:

(Sorry, I don't know how to embed code, so I have to write it)

player.h (the code I'm having problems with):

 class Player{ private: static int potions; public: int getPotions(); } 

player.cpp (again, the code I came across):

 int Player::potions; int Player::getPotions(){ Player player; return player.potions; } 

I probably forgot some pieces of code, such as return, etc., but this is because I have a small amount of time to ask this question, so I put the parts related to my problem.

+4
source share
2 answers

First, you are trying to return a member of the static class class as if it were an instance element of an object. Static elements are denoted by the symbol Class::member , not object.member .

Secondly, I don’t think you want potions be static. Static members are shared between all objects in the class. Therefore, if player A has 100 health potions, then player B will have the same 100 health potions.

Third, you declare Player::potions at the top of your .cpp file. I do not think you want. The potions element potions already been declared in your .h file.

player.h:

 class Player { private: int potions; public: int getPotions(); }; 

player.cpp:

 int Player::getPotions() { return potions; } 

If you want potions be static, change it to:

 return Player::potions; 
+6
source

Try to change

 Player player; return player.potions; 

just

 return potions; 

You create a new player and return this potion for the object, not the potion of the "this" object.

+1
source

Source: https://habr.com/ru/post/1439507/


All Articles