simple static question

Started by
1 comment, last by saeedm 16 years, 1 month ago
In my class Vertex I'd like to keep a static variable std::vector<int> dists, and manipulate it from the functions in Vertex. The solutions I have found online are giving me errors (Im working in dev-c++ with Mingw/GCC). Here is what I have tried: //Vertex.h// class Vertex { private: static std::vector<int> dist; public: Vertex(int); int getDist(); }; //Vertex.cpp// Vertex::Vertex(int i) { Vertex::dist = i; } int Vertex::getDist() { return Vertex::dist; I get a linker error - undefined reference to Vertex::dists Thanks for any help
Advertisement
Short answer:
In your CPP file you must put:
std::vector<int> Vertex::dist;

Long answer:
Writing "static type name;" in a header file tells the compiler that there is a static variable of called 'name' *somewhere* that it can use. But this doesn't tell it where to allocate the storage space for the variable.
You must put the above (short-answer) code in a source file, which tells the compiler which code-module the variable's storage will be located. Otherwise, as you've discovered, when the linker tries to assemble your program, it wont be able to find where that variable is supposed to be stored ;)
It worked - thanks!

This topic is closed to new replies.

Advertisement