Static variable initialization in C ++ class

Source: Internet
Author: User

First, the static variable is initialized only once, whether in the class or in the function... there is such a function:

Void Foo () <br/>{< br/> static int A = 3; // initialize <br/> STD: cout <; <br/> A ++; <br/>}

Here, static int A = 3 is executed only once. Call Foo () twice in main and the result is 34. Change the above function

Void Foo () <br/>{< br/> static int A; <br/> A = 3; // not initialize <br/> STD :: cout <A; <br/> A ++; <br/>}

It is also called twice in Foo (). The result is 33.

Use non-const static class member variables in the class. Use the form of typename classname: variablename = value during initialization

For example:

Class myclass <br/>{< br/> Public: <br/> static int A; <br/> myclass () <br/>{< br/>}< br/>}; <br/> int myclass: A = 3; // here initialize <br/> int main () <br/>{< br/> cout <myclass: A; <br/> return 0; <br/>}

If you are using a static variable of the const type, initialize the variable in the class:

Class myclass <br/>{< br/> Public: <br/> const static int A = 3; // here initialize <br/> myclass () <br/>{< br/>}< br/> };

If non-const static variables are used in the template, You need to initialize them according to the specific type.

For example, int myclass <int >:: A = 4; if you call cout <myclass <double>: A, the compilation will fail.

Because the template is of a specific type, myclass <int> and myclass <double> are a specific type, and a static class member is initialized once in a specific class. This is easy to understand.

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.