How is this private variable "not declared in this scope"?

I am currently trying to learn more about object oriented design in C ++ (familiar with Java) and I am running into some walls. The project I'm trying to put together to learn these principles in a game built using SFML for graphics and sound. I have the following two files.

WorldObject.h

#ifndef WORLDOBJECT_H #define WORLDOBJECT_H #include <SFML/Graphics.hpp> #include <string> #include "ImageManager.h" class WorldObject { private: sf::Sprite _sprite; void SetImagePath(std::string path); sf::Sprite GetGraphic(); }; #endif 

WorldObject.cpp

 #include "WorldObject.h" void WorldObject::SetImagePath(std::string path) { _sprite.SetImage(*gImageManager.getResource(path)); } sf::Sprite GetGraphic() { return _sprite; } 

I do not see any problems with them, but when I try to compile them, I get the following error from g ++:

 WorldObject.cpp: In function 'sf::Sprite GetGraphic()': WorldObject.cpp:9: error: '_sprite' was not declared in this scope make: *** [WorldObject.o] Error 1 

What am I missing in this code? Trying to figure out the right way to set up the inheritance hierarchy has caused most problems so far in game development, but I know that this is primarily due to the fact that I am more likely to use the Java inheritance model rather than the C ++ multiple inheritance model.

+4
source share
5 answers

The GetGraphics function that you define in WorldObject.cpp is not a member of the WorldObject class. Use

 sf::Sprite WorldObject::GetGraphic() { return _sprite; } 

instead

 sf::Sprite GetGraphic() { return _sprite; } 

Note that the C ++ compiler only complains about the missing WorldObject::GetGraphic if this function is called somewhere in your program.

+9
source

sf::Sprite GetGraphic() is incorrect, it declares a global GetGraphic function. Since GetGraphic is a function of the class WorldObject , it should be sf::Sprite WorldObject::GetGraphic() .

+2
source

I have not done much C ++, but I think you need WorldObject::GetGraphic instead of GetGraphic in WorldObject.cpp?

0
source

I suppose you mean:

sf :: Sprite WorldObject :: GetGraphic ()

not

sf :: Sprite GetGraphic ()

in WorldObject.cpp

0
source
 // `GetGraphic()` is a member function of `WorldObject` class. So, you have two options to correct- //Either define the functionality of `GetGraphic()` in the class definition itself. #ifndef WORLDOBJECT_H #define WORLDOBJECT_H #include <SFML/Graphics.hpp> #include <string> #include "ImageManager.h" class WorldObject { private: sf::Sprite _sprite; void SetImagePath(std::string path); sf::Sprite GetGraphic() // Option 1 { return _sprite; } }; #endif //When providing the member function definition, you need to declare that it is in class scope. // Option 2 => Just prototype in class header, but definition in .cpp sf::Sprite WorldObject::GetGraphic() { return _sprite; } 
0
source

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


All Articles