[英]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: 如果我有一个具有静态const数据成员的类,那么初始化它的最佳方法是什么:
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. 如您在上面第一次看到的那样,我使用类内初始化程序初始化了
PI_
,然后在没有任何初始化程序的类外定义了PI_
。
And in the second I just declared it inside the class without initializer and defined it outside the class with an initializer. 在第二个中,我只是在没有初始化程序的类内声明了它,并在带有初始化程序的类外定义了它。
PI_
outside the class redundant as long as I provided an in-class initializer? PI_
定义是否多余? Can I say that providing an in-class initializer for a const static data member is considered a "definition" rather than "declaration"? 我能否说为const静态数据成员提供类内初始化程序被视为“定义”而不是“声明”?
Also in "C++ primer 5th ed: 也在《 C ++入门》第5版中:
" *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.*
" “
*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 您最好只使用constexpr,这意味着您可以将其全部保留在类定义中
class Circle{
public:
//...
private:
static constexpr double PI_ = 3.14; // 1
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.