C/C++, static

0. General speaking

static is a keyword in C++, and it can be used in variables, functions, and members of a class. 

1. static members of a class

static data member

static member functions

 

2. Define a static member

//account.h

class Account {

public: 

    static double rate();

    void applyint();

private:

    double  amount;

    static double initRate;

};

// account.cpp

double Account::rate(){  //no need to specify the static again 

  /* do something */

 

3. Initialize the static member variable

    

3. Call the static member

Account ac1; 

Account *pac = new Account();

double tmp; 

tmp = ac1.rate();  // through an object

tmp = pac->rate(); // through a pointer to an object

rate = Account::rate(); // through the class using the scope operator

 

4. Key points to use static keyword

static functions have NO this pointer;

static functions may not be declared as virtual;

declaring a member function as const is a promise not to modify the object of which the function is a member; 

static data members must be defined (exactly once) outside the class body;

上一篇:什么是图像分类的Top-5和Top-1错误率


下一篇:How to solve mysql warning: “InnoDB: page_cleaner: 1000ms intended loop took XXX ms. The settings mi