I'd like to access a static map that is stored in a seperate class and iterate through and print the contents.
So I have three files:
HasGlobals.cpp which has the global map.
/* HasGlobals.cpp */
#include <string>
#include <map>
#include <iostream>
class HasGlobals{
public:
static std::map<int, std::string> globalData;
HasGlobals(){
globalData.insert(std::pair<int, std::string>(0, "data"));
};
~HasGlobals(){
};
};
WantsGlobals.cpp which has a method that needs to use the map from HasGlobals.cpp for one of its methods.
/* WantsGlobals.cpp */
#include "HasGlobals.cpp"
#include <string>
class WantsGlobals{
public:
WantsGlobals(){
};
~WantsGlobals(){
};
//THIS IS THE METHOD THAT I CAN'T GET TO WORK
void printContentsOfGlobal(){
HasGlobals * globalRetriever = new HasGlobals();
for(std::map<int, std::string>::iterator it = globalRetriever->globalData.begin(); it != globalRetriever->globalData.end(); ++it){
std::cout << it->first << " " << it->second << std::endl;
}
};
};
Main.cpp which simply tries to call the printContentsOfGlobal() method in WantsGlobals.cpp.
/* Main.cpp */
#include <iostream>
#include "WantsGlobals.cpp"
int main(){
WantsGlobals * globalRetriever = new WantsGlobals();
globalRetriever->printContentsOfGlobal();
}
Right now this code doesn't compile and gives me
undefined reference to 'HasGlobals::globalData'
How would I implement printContentsOfGlobal() so that I can retrieve the data in the map[globalData] in the seperate HasGlobals.cpp file?
EDIT: Thanks for the help everyone. Below is the code I created with everyone's help. Yes it's still not perfect but it compiles and performs the desired behavior:
HasGlobals.hpp
#include <string>
#include <map>
#include <iostream>
class HasGlobals{
public:
static std::map<int, std::string> globalData;
HasGlobals(){};
~HasGlobals(){};
static std::map<int, std::string> createDummyData(){
std::map<int, std::string> m;
m[0] = "Help";
m[1] = "Me";
m[2] = "Stackoverflow";
m[3] = "You're my only hope.";
return m;
}
};
std::map<int, std::string> HasGlobals::globalData = HasGlobals::createDummyData();
WantsGlobals.hpp
#include "HasGlobals.hpp"
#include <string>
#include <map>
class WantsGlobals{
public:
WantsGlobals(){};
~WantsGlobals(){};
void printContentsOfGlobal(){
for(std::map<int, std::string>::iterator it = HasGlobals::globalData.begin(); it != HasGlobals::globalData.end(); ++it){
std::cout << it->first << " " << it->second << std::endl;
}
};
};
Main.cpp
#include <iostream>
#include <"WantsGlobals.hpp">
int main(){
WantsGlobals * globalRetriever = new WantsGlobals();
globalRetriever->printContentsOfGlobal();
}