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;

5. Static in C

A static variable inside a function keeps its value between invocations. eg:

void foo(){

  static int sa = 10;  // sa will accumulated. sa will be allocated in the data segment rather than in the stack 

  int a = 5;

  sa += 2;

  a += 5;  // no matter how many times we call this function, a will be the same

}

int main(){

  for(int i = 0; i < 10; ++i){foo();}

  return 0;

}

static global variable are not visible outside of the C file they are defined in. 

static functions are not visible outside of the C file they are defined in.

A static variable inside a function keeps its value between invocations.

In the C programming language, static is used with global variables and functions to set their scope to the containing file.

In local variables, static is used to store the variable in the statically allocated memory instead of the automatically allocated memory.

While the language does not dictate the implementation of either type of memory, statically allocated memory is typically reserved in the data segment of the program at compile-time, while the automatically allocated memory is normally implemented as a transient call stack

原文地址:https://www.cnblogs.com/sarah-zhang/p/12230151.html