0

I need a class with static std::vector<int> simples (first N simple numbers). I created it in static method __init__, which is called before any instance of MyClass is created:

class MyClass
{
public:
    MyClass()
    {
        /* I need to use MyClass::simples here */
        printf("%d\n", (int)MyClass::simples.size());
        /* But I get the error here :( */
    }

    static void __init__(int N)
    {
        simples.push_back(2);
        /* ...
           here I compute first N simple numbers and fill 
           MyClass::simples with them
        */
    }

private:
    static std::vector<int> simples;
};

int main()
{
    MyClass::__init__(1000);
    MyClass var;

    return 0;
}

But when I tried to use this vector in construction, I get undefined reference to 'MyClass::simples' error. How to solve my problem?

Vladyabra
  • 35
  • 1
  • 6

2 Answers2

1

When defining a static member in C++, you need to write it two times: first in class definition as you did:

static std::vector<int> simples;

And then outside (preferably in an external .cpp file):

std::vector<int> MyClass::simples;

If you know about C language, this can help you: static members in C++ are comparable from global variables in C: defined as a prototype in .h file included whenever you need it, and value initialized in one .c/.cpp file.

Aracthor
  • 5,757
  • 6
  • 31
  • 59
0

You have to define the static data member outside the class

std::vector<int> MyClass::simples;

Within the class definition it is only declared.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335