static int in C ++ class

0

Hello, the following code is displaying the error to the right:

#include <iostream>

using namespace std;

class teste {
    static int x;
    public:
        teste () {
            x++;
        }
}  t1;

int main () {

    return 0;
}

I declare the static variable int, and in the constructor method I increment +1, but the following error occurs.

How to solve?

NOTE: In the book I'm reading the code is like that too.

    
asked by anonymous 17.06.2018 / 05:21

1 answer

3

Static data members are stored separately, as if they were not part of the object. So they must declare themselves out of their class.

class teste {
    static int x;
    public:
        teste () {
            x++;
        }
}  t1;

int teste::x = 0;
    
17.06.2018 / 20:40