how to correct it so I can display the static int by
cout<<A::a<<endl;
like in an example below?
#include <iostream>
using namespace std;
class A{
public:
static int a = 0;
};
int main()
{
cout << A::a << endl;
return 0;
}
Inside the class definition, the static members are only declared and not defined. By default, only definitions have initialization, with the exception that for static constants of integral types the declaration can have the initialization.
The problem in your program is that the static member is used (std::cout << A::a is odr-use for non-const static member attributes), but you have no definition. You need to define the variable in a single translation unit in your program by adding:
int A::a = value;
(Note that because the static member is not const, you cannot provide an initializer inside the class definition, so you need to remove the = 0 from the declaration in class definition. Also note that you can skip the = value in the initialization if value == 0, as static initialization will set A::a to 0 before any other initialization)
Either:
class A{
public:
static const int a = 0;
};
(const integral types can be initialized inside the class definition)
or
class A{
public:
static int a;
};
int A::a = 0;