Static data members and static member functions

Source: Internet
Author: User

Static properties are not owned by each object in the class, but are common. Because a static member escapes the nature of the object, the entity should be generated before all objects are produced, and it is more appropriate to initialize it when the program starts. Do not repeat static when initializing, but add class name space. The entity's uniqueness in the program requires that he cannot be placed in the header file with the definition of the class, but it is indeed a member of the class, so it is most appropriate to put it in a class implementation. As follows:

--------------------Student.h---Class-defined files

Class student{

Private

static int num;

}

-------------------files implemented within the Student.cpp---

#include "Student.h"

student::number=0;

Because static data members do not belong to any one object, static data members are defined as private for security reasons, so how do you access it? The same can be defined by a static member function to access it, static member functions to access the static data is most appropriate, declare a static member function in the class, to precede the member function with the static keyword, you can use the object to call him, can also be called with the revolver domain operator. Static member functions should be implemented at the same location as the member function, and should be removed from static when implemented outside the class, but the domain operator is required.

--------------------Student.h---Class-defined files

Class student{

Private

static int num;

Public

static void Print ();

}

-------------------files implemented within the Student.cpp---

#include "Student.h"

student::number=0;

void Student::P rint () {

cout<<num++<<endl;

}

Static data members and static member functions

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.