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;

猜你喜欢

转载自www.cnblogs.com/sarah-zhang/p/12230151.html