C++ static member variables and static member functions

1. Static member variables

1) Define static member variables

 The keyword static can be used to describe the members of a class, and static members provide a sharing mechanism for objects of the same
type
 A static member is local to the class, it is not an object member

例如:
#include<iostream>
using namespace std;
class  counter
{     
static  int  num ; //声明与定义静态数据成员
  public :
      void  setnum ( int i ) { num = i ; }   //成员函数访问静态数据成员
      void  shownum() { cout << num << '\t' ; }
} ;
int  counter :: num = 0 ;//声明与定义静态数据成员
void main ()
{   counter  a , b ;
    a.shownum() ; //调用成员函数访问私有静态数据成员
    b.shownum() ;
    a.setnum(10) ;
    a.shownum() ;
    b.shownum() ;
}

2) Use static member variables

// 例  使用公有静态数据成员 
#include<iostream.h>
class  counter
{ public :
      counter (int a) { mem = a; }
      int mem;      //公有数据成员
      static  int  Smem ;   //公有静态数据成员
} ;
int  counter :: Smem = 1 ;  //初始值为1 
void main()
{   counter c(5);
    int i ;
    for( i = 0 ; i < 5 ; i ++ )
      { counter::Smem += i ;
         cout << counter::Smem << '\t' ;  //访问静态成员变量方法2
      }
    cout<<endl;
    cout<<"c.Smem = "<<c.Smem<<endl; //访问静态成员变量方法1
    cout<<"c.mem = "<<c.mem<<endl;
}

2. Static member functions

1) Concept

 The number of static member functions is prefixed with the keyword static
The static member function provides common operations that do not depend on the class data structure, it does not have this pointer
object call

2) Case

#include <iostream>
using namespace std;

class X{
int DataMem;
public:
    static void StaFun(int i,X *p);
};
void X::StaFun(int i,X *p)
{
    p->DataMem=i;
}
void g()
{
    X x;
    X::StaFun(1,&x);
    x.StaFun(1,&x);
}

3) Difficult problems: In static member functions, ordinary variables cannot be used.

//静态成员变量属于整个类的,分不清楚,是那个具体对象的属性。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325481320&siteId=291194637