Can anyone explain why following code won't compile? At least on g++ 4.2.4.
And more interesting, why it will compile when I cast MEMBER to int?
#include <vector>
class Foo {
public:
static const int MEMBER = 1;
};
int main(){
vector<int> v;
v.push_back( Foo::MEMBER ); // undefined reference to `Foo::MEMBER'
v.push_back( (int) Foo::MEMBER ); // OK
return 0;
}
You need to actually define the static member somewhere (after the class definition). Try this:
class Foo { /* ... */ };
const int Foo::MEMBER;
int main() { /* ... */ }
That should get rid of the undefined reference.
Good point, inline static const integer initialization creates a scoped integer constant which you can't take the address of, and vector takes a reference param.
This answer only addresses the first part of the question. The second part is much more interesting: Why does adding a NOP cast make it work without requiring the external declaration?
I just spent a good bit of time figuring out that if the class definition is in a header file, then the allocation of the static variable should be in the implementation file, not the header.
@shanet: Very good point--I should have mentioned that in my answer!
But if I declare it as const, is it not possible for me to change the value of that variable?