简体   繁体   中英

Should I initialize static const data member with in-class initilizer or in its definition outside class?

If I have a class that has a static const data member then what is the best way to initialize it:

class Circle{
    public:
        //...
    private:
        static const double PI_ = 3.14; // 1
        //static const double PI_; // 2
};

double Circle::PI_; // 1   is this redundant?
//double Circle::PI_ = 3.14;

As you can see above in first time I initialized PI_ with in-class initializer and then I defined it outside the class without any initializer.

And in the second I just declared it inside the class without initializer and defined it outside the class with an initializer.

  • Which is the best way?
  • Is the definition of PI_ outside the class redundant as long as I provided an in-class initializer?
  • Can I say that providing an in-class initializer for a const static data member is considered a "definition" rather than "declaration"?

  • Also in "C++ primer 5th ed:

    " *If the member is used only in contexts where the compiler can substitute the member's value, then an initialized const or constexpr static need not be separately defined. However, if we use the member in a context in which the value cannot be substituted, then there must be a definition for that member. For example, if the only use we make of period is to define the dimension of daily_tbl, there is no need to define period outside of Account. However, if we omit the definition, it is possible that even seemingly trivial changes to the program might cause the program to fail to compile because of the missing definition. For example, if we pass Account::period to a function that takes a const int&, then period must be defined.* "

But I tried it and worked without definition outside the class?!!!

Thank you!

You'd be better off just using constexpr, which means you can keep it all within the class definition

class Circle{
public:
    //...
private:
    static constexpr double PI_ = 3.14; // 1
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM