Whenever we have a class with some static member variable, why do we need to define it?
Why can't we use it directly?
I wanted to see if any memory space would be allocated to the static variable if I don't define it, so I wrote this little code and it seems like memory is indeed allocated for the variable.
#include <iostream>
using namespace std;
class A
{
public:
int a;
static int b;
};
// int A::b = 1;
int main()
{
cout<<sizeof(A::b);
return 0;
}
Output:
4
Now, I defined the variable and initialized it (uncommented the int A::b = 1; line) and ran the same code, even this time the output was the same.
So, what is the purpose behind defining it?
question from:
https://stackoverflow.com/questions/65879919/why-do-we-need-to-define-a-static-variable-of-a-class-unlike-the-other-member-o 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…