Undefined reference in static class member

Asked 1 years ago, Updated 1 years ago, 94 views

Why do I get a compilation error in my code? And why does it work well if you convert MEMBER to int without code 1? (compiled in g++ 4.2.4)

#include <vector>

class Foo {  
public:  
    static const int MEMBER = 1;  
};

int main(){  
    vector<int> v;  
    v.push_back (Foo::MEMBER); // 1. No - undefined reference to 'Foo::MEMBER'
    v.push_back((int)Foo::MEMBER); // 2. Good for you 
    return 0;
}

undefined reference to 'Foo::MEMBER'

c++ g++

2022-09-22 08:23

1 Answers

The static member must be defined after the class definition. If you do it like the code below, the error will disappear

class Foo { /* ... */ };

const int Foo::MEMBER;

int main() { /* ... */ }

The reason why I have to do this is static This is because the lifetime of a member variable starts from the time it is called, not from the start of the program.

For example,

class Foo {
public:
    Foo(){
        cout << "Foo!!!!!" << endl;
    }
};

class Bar {
public:
    static const Foo foo;
};

//Annotation processing
//const Foo Bar:: foo;

int main(){
    return 0;
}

This code will exit the program with nothing output, even though the bar has static const Foooo. However, if you remove the annotation of const Foo Bar::foo; between the bar class and main, foo!!!!! will be output and the program will exit.

If you convert the type to (int), a temporary object of type Bar is created in the middle This is because it has the same effect as the previous const Foo Bar::foo;.


2022-09-22 08:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.