Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

c++ - Why do we need to define a static variable of a class, unlike the other member of a class?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For static data member you have to allocate memory for it in your implementation, what you are doing now does not allocate memory but you are just getting the size of the int. In C++ 17 you can declare static variable inline, for int its default value is zero but you can set any value you want. Like this:

 static inline int b=4;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...