zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Hibernate学习笔记(一)
    mysql内联接、左联接、右联接
    mysql表数据增删改查、子查询
    mysql建表时候的五种约束
    mysql数据库基本数据类型
    nginx uwsgi flask相关配置
    关于爬虫数据的解析器设计
    Redis 七月小说网的爬虫缓存设计
    MariaDB 数据库迁移
    React Relay 实现
  • 原文地址:https://www.cnblogs.com/sarah-zhang/p/12230151.html
Copyright © 2011-2022 走看看