The use of static member variables and static member functions in C + + classes

Source: Internet
Author: User

Code:

1#include <iostream>2#include <string>3#include <cstdio>4 5 using namespacestd;6 7 classa{8      Public:9         Static intA;Ten         //static int a = 0;//compilation does not pass and cannot be initialized within a class One         intb; A         Static voidfunc1 () { -cout<<"static Func"<<Endl; -a++; the             //b++; -         } -         voidFunc2 () { -cout<<"normal func"<<Endl; +a++; -b++; +         } A }c; at intA::a =0;//compilation can be initialized outside of the class -  - intMainintargcChar*argv[]) { -  - c.func1 (); - C.func2 (); in  -     return 0; to}

Output:

Static Funcnormal func

Analysis:

1. Static member variables cannot be initialized in a class and need to be initialized outside of the class.

2, static member functions can only access static member variables, ordinary member functions do not have this restriction.

3. A static member function cannot be a virtual function.

The use of static member variables and static member functions in C + + classes

Related Article

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.