How to initialize a static const member in C++?

后端 未结 4 1636
陌清茗
陌清茗 2020-11-29 00:08

Is it possible to initialize a static const value outside of the constructor? Can it be initialized at the same place where member declarations are found?

cl         


        
4条回答
  •  半阙折子戏
    2020-11-29 00:39

    YES you can but only for int types. If you want your static member to be any other type, you'll have to define it somewhere in a cpp file.

    class A{
    private:
     static const int a = 4; // valid
     static const std::string t ; // can't be initialized here
     ...
     ...
    };
    
    
    // in a cpp file where the static variable will exist 
    const std::string A::t = "this way it works";
    

    Also, note that this rule have been removed in C++11, now (with a compiler providing the feature) you can initialize what you want directly in the class member declaration.

提交回复
热议问题