SFML community forums
Help => Graphics => Topic started by: Pyrius on October 18, 2011, 12:39:36 pm
-
I have a class which handles all of the drawing so far, so it has sf::Image's and sf::Sprite's. Those objects will always be the same, so I want to declare them static instead of loading the images and giving the sprites images in the constructor and accessing them with an object of that class. I want to do something like this:
class Foo
{
public:
static void loadImages();
private:
static sf::Image image;
static sf::Sprite sprite;
};
Then in loadImages():
void Foo::loadImages()
{
Foo::image.LoadFromFile("image.png");
Foo::sprite.SetImage(image);
}
But I can't compile it. I get the following errors:
"undefined reference to 'Foo::image'"
"undefined reference to 'Foo::sprite'"
I'm still learning about the static keyword, so I guess it's just a syntax error.
-
I'm still learning about the static keyword
Google is often more helpful (and quick) than posting on a forum and waiting for an answer, especially for such a basic C++ problem ;)
http://tinyurl.com/692z3ds
-
Hehe lmgtfy.com is awesome. I tried googling it but didn't get an answer. I didn't think about googling "undefined reference" for some reason...
-
Don't you have a C++ book you learn with? If not, you should really buy or borrow a good one (like the C++ Primer), so that basics like the static keyword get explained in details. This is much more effective than when you have to google everything, and it leaves less knowledge gaps ;)
-
Nope, I don't; I learned the basics through TheNewBoston (thenewboston.com), and I didn't learn static. Or, maybe I did, and I forgot about it.
EDIT: I give myself challenge programs to complete and when I need to know how to do something for that program that I don't know yet I look it up, and if I can't find an answer, I use the forum on cplusplus.com to ask for an answer.
-
You also should declare the static members outside the class.
Foo.cpp
sf::Image Foo::image;
sf::Sprite Foo::sprite;
-
You also should declare the static members outside the class.
Foo.cpp
sf::Image Foo::image;
sf::Sprite Foo::sprite;
No, they should be declared inside the class in the interface file Foo.h
class Foo {
private:
static sf::Image image;
static sf::Sprite sprite;
}
and then defined (and initialised via default ctors) in the implementation file Foo.cpp
sf::Image Foo::image;
sf::Sprite Foo::sprite;
Declaration is where the name and type of a something is made known to the compiler.
Definition (for objects) is where memory is set aside for the variable.
-
Yup, I found that out :). Thanks for responding.