In C + +, you can declare a static member object, but at this point it simply declares that there is no definition and that the internal static member object is not created. This object can be created only after the class body is externally determined.
1#include <iostream>2 usingstd::cout;3 usingStd::endl;4 classouter{5 classinner{6 Public:7 inner () {8cout <<"Inner ()"<<Endl;9 }Ten~inner () { Onecout <<"~inner ()"<<Endl; A } - - }; the Staticinner M_inn; - Public: - - Outer () { +cout <<"Outer ()"<<Endl; - } +~Outer () { Acout <<"~outer ()"<<Endl; at } - }; - - intMain () { - Outer O1; - return 0; in -}
In the code above, we do not define the member object, just a referential declaration, and we do not allocate space for it at this time. The operation results are as follows
We see that the running results show that the constructors and destructors of inner are not called, stating that the object M_inn is not created inner;
At this point we define the M_inn outside the class body
The code is as follows
1#include <iostream>2 usingstd::cout;3 usingStd::endl;4 classouter{5 classinner{6 Public:7 inner () {8cout <<"Inner ()"<<Endl;9 }Ten~inner () { Onecout <<"~inner ()"<<Endl; A } - - }; the Staticinner M_inn; - Public: - - Outer () { +cout <<"Outer ()"<<Endl; - } +~Outer () { Acout <<"~outer ()"<<Endl; at } - }; -Outer::inner Outer::m_inn;//define the M_inn. - intMain () { - Outer O1; - return 0; in -}
The results of this operation indicate that the M_inn was created. So if there are static member objects inside the class, be sure to define them outside the class body
Static member objects for classes in C + +