C ++ static member and static member

Source: Internet
Author: User

C ++ static member and static member

URL: http://www.cnblogs.com/archimedes/p/cpp-static2.html

Static Data Member

Definition:

Data member declared with the keyword static

class Box{public:    int volume() const;private:    int iwitch;    int length;    int heigth;    static int count;};

Initialization:

Static data members must be initialized and can only be initialized outside the class. static data cannot be added during initialization. format:

Type Class Name: static data member name [= initial value];

Class Box {public: int volume () const; private: int iwitch; int length; int heigth; static int count ;}; int Box :: count; // It must be initialized outside the class

Note: it cannot be initialized through the constructor or through the initialization list.

Access:

Static data members belong to Classes rather than specific objects, which are shared by different objects. Therefore, there are two access methods for public static data members outside the class.

Class Name: public static data member

Object Name. Public static data member

Static data members can be directly referenced by any member functions of their classes.
void Box::display()const{     cout << Box:: s_iCount << " ";     cout << s_iCount << " ";}

Storage:

The memory unit is opened during compilation of static data members, which can be used before the Objects occupying the global zone class are created.

The memory units of static data members are independently opened. They do not belong to a specific object and are shared by different objects.

Why should I introduce static data members?

Data between objects can be shared through communication channels. In C ++, when data is shared between objects, static data members should be used instead of global variables, because global variables cannot reflect encapsulation features.

#include <iostream>using namespace std;class Type{public:    Type(int ax=0);    static int s_value;    void print();private:    int m_value;};int Type::s_value;Type::Type(int ax){    m_value=ax;}void Type::print(){    cout<<"m_value="        <<++m_value        <<endl;    cout<<"s_value="        <<++s_value        <<endl;}int main(){    Type::s_value=90;    Type c1,c2;    c1.print();    c2.print();    system("PAUSE");    return 0;}

Example: count the number of created objects

#include <iostream>#include <string>using namespace std;class student{public:    student(string aName="codingwu")    {        strName=aName;        count++;        cout << "Cons"<<" "<<strName <<endl;    }    ~student()    {        count--;        cout<< "Des"<<" "<<strName<<endl;    }    void printCount()const    {        cout<<"COUNT = "<<count<<endl;    }private:    static int count;    string strName;};int student::count;int main(){    student stu("li");    student stu1("zhang");    student *p=new student[5];    delete []p;    student("hahahaha");    stu.printCount();    system("PAUSE");    return 0;}

Running result:

Static member functions

1. concept:

Member functions declared using static

2. access method:
Belongs to the class type rather than a specific object

3. Features

① Static member functions are used to access static members (including data members and member functions)

② It belongs to a class rather than a specific object. Therefore, it can be accessed through the class name or referenced by the object name.

③ In fact, static member functions are global functions in the class.

④ The static member function does not have the this pointer
#include <iostream>using namespace std;class Type{public:    static void print();    Type(int aValue = 0);private:    int m_iValue;    static int s_iValue;};int Type::s_iValue;Type::Type(int aValue){      m_iValue = aValue;    s_iValue++;}void Type::print(){      //cout << ++m_iValue;//Error    cout << s_iValue << endl;}int main(){     Type::print();     Type c1,c2;     c1.print();      c2.print();      return 0;}

Note:

Non-static member functions can access any member in this class.

Static member functions are used to access static members and cannot directly access non-static members.

# Include <iostream> # include <string> using namespace std; class Student {public: Student (int aNum = 0, int aAge = 0, double aScore = 0 ); void total (); static double s_average (); double m_iScore; private: static int s_iCount; // number of objects static double s_iSum; // total score int m_iNum; int m_iAge ;}; double Student: s_iSum; int Student: s_iCount; Student: Student (int aNum, int aAge, double aScore): m_iNum (aNum), m_iAge (aAge ), m_iScore (aScore) {} void Student: total () {s_iSum + = m_iScore; s_iCount ++;} double Student: s_average () {return s_iSum/s_iCount ;} int main () {Student stud [3] = {Student (1001,18, 60), Student (1002,19, 90), Student (1005,20, 0 ),}; for (int I = 0; I <3; I ++) stud [I]. total (); cout <Student: s_average () <endl; system ("PAUSE"); return 0 ;}

 

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.