What is the difference between a static and const variable?

前端 未结 17 1792
天命终不由人
天命终不由人 2020-11-29 18:39

Can someone explain the difference between a static and const variable?

17条回答
  •  臣服心动
    2020-11-29 18:58

    Static variables in the context of a class are shared between all instances of a class.

    In a function, it remains a persistent variable, so you could for instance count the number of times a function has been called.

    When used outside of a function or class, it ensures the variable can only be used by code in that specific file, and nowhere else.

    Constant variables however are prevented from changing. A common use of const and static together is within a class definition to provide some sort of constant.

    class myClass {
    public:
         static const int TOTAL_NUMBER = 5;
         // some public stuff
    private:
         // some stuff
    };
    

提交回复
热议问题