C ++ programming language design - the third job
Chapter V heavy and difficult to analyze knowledge
Static members of a class - a knowledge point
definition:
Static member, referring to the declaration can be added in c ++ class member static member keywords, such statement is called static members (including the data members and member functions). That is declared a class member, or will be able to share the static member functions within the scope of the class.
- Source: Baidu Encyclopedia · static member
purpose:
Resolved between different objects of the same class and function data sharing
advantage:
Can both share and protect data
Static data members
Static data member static survival. Since the static data members do not belong to any object, so it can be accessed via the class name, general usage is " class name :: identifier ."
Static member function
Static member function can directly access static data and function members of the class. The access non-static members must pass the object name.
Second, code examples - Point class with static data and function members
class Point{ //Point类定义
public:
Point(int x=0,int y=0):x(x),y(y){
count++;
}
Point(Point &p){
x=p.x;
y=p.y;
count++;
}
~Point(){count--;}
int getX(){return x;}
int getY(){return y;}
static void showCount(){ //静态函数成员
cout<<" Object count="<<count<<endl;
}
private:
int x,y;
static int count; //静态数据成员
};
int Point::count=0; //静态函数成员的定义和初始化,直接使用类名限定
int main(){
Point a(4,5);
cout<<"Point A: "<<a.getX()<<","<<a.getY();
Point::showCount();//静态函数成员的调用,不依赖于任何对象
Point b(a);
cout<<"Point B: "<<b.getX()<<","<<b.getY();
Point::showCount();//同上,不依赖于任何对象
return 0;
}
operation result:
Third, the analytical results
Experimental results show that the use of a static member of the class, a good solution between different objects and data sharing functions