static class member of class's own type [dupli

2019-01-25 14:07发布

Possible Duplicate:
Do static members of a class occupy memory if no object of that class is created?
Memory Allocation of Static Members in a Class

"A class is not considered defined untill its class body is complete, a class can not have data members of its own type. A class can have data members that are pointers/reference to its own type."

  • C++ Primer (Lippman Lajoie)

Makes sense.

But why is this allowed then ?

class justAClass
{
     public  : 
     justAClass();

     private :          
     static justAClass justAMember;
}

For pointers it is understandable. But how will this above thing work ? How will i ever decide the size for object of such a class ? Isnt it a recursive case (with no base condition) to have a member of its own type, even if it is static ?

2条回答
走好不送
2楼-- · 2019-01-25 14:44

The reason for class can't have data members of its own type is the compiler must know the size of class object. For example, one class is a local variable in function, the compiler can handle the stack only it knows the class size.

For your case, the static class member doesn't reside in class object, so has no impact to size of class object. It's OK.

查看更多
Emotional °昔
3楼-- · 2019-01-25 14:52

Formally, the distinction is that the declaration of a static member in a class is not a definition. You must provide a definition elsewhere (exactly once), and the compiler doesn't need to know the size until it encounters the definition. Static members do not impact on the size of the class itself. (In many ways, the static member declaration in the class is very much like an extern non-member declaration.)

查看更多
登录 后发表回答