Static member objects for classes in C + +

Source: Internet
Author: User

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 + +

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.