staticconstint LENGTH = 8;
static Image* imgs[LENGTH];
static string imgnames[LENGTH] = {"Magician","Ogre","Bowman","Warrior","alien","turtle","bird","king_frog"};
class GuiManager{
private:
public:
static Image* getImage(string name){
cout << "array: " << endl;
for (int i = 0; i < LENGTH; i++){
cout << imgs[i] << endl;
}
for (int i = 0; i < LENGTH; i++){
if (imgnames[i] == (name)){
cout << "returning :" << imgs[i] << ":" << i;
return imgs[i];
}
}
cout << "RETURNING NULL";
return NULL;
}
staticvoid initImages(){
for (int i = 0; i < LENGTH; i++){
imgs[i] = new Image("C:/Users/Andreas/C++ Workspace/Textbase/src/"+imgnames[i]+".txt");
cout << "set to: " << imgs[i];
}
}
}
Now what I do is I call initImages upon start.
Then I get the image pointer by giving the name of the imagefile (its ascii images)
I also print out the address of the Image objects when I init them and when Im using getImage function.
Problem is:
When I run the init function. It prints all the addresses (non of them are null).
But when I use getImage() it also prints all addresses of same array, but now they are all 0!
Is my computer removing content without my approval or what?
P.S It never prints Returning null. It can locate the correct index depending on name so thats not the issue.
static does not do what you think it does for global variables. What happens is that each cpp file has it's own copy of a static var. So you may be loading the image in one file... but then another file will still see it as null because their copy of the var did not change.
c++ is not friendly with class definition and implementation are in the same cpp file. use your code as example, users need to include your cpp file directly. but since you do not have a #ifdef ... #endif or #pragma once protection, there could be several instances of your class definition and implementation in different .o files, when you try to link these .o files together, no lucky, you surely cannot.
so first of all, separate your definition and implementation. and I am afraid, you missed a ; at the end of class.
the definition in c++ only shows 'there is something', while the instantiation tells the binary file how to create the instance. so if you really need to use global variables, you can DECLARE it in several places with 'extern' keyword. but you may not like this keyword, if you tried to use it.
the definition can only show once with a variable, the declaration can show several times, but the instantiation can only show once.