【发布时间】:2019-11-20 14:57:17
【问题描述】:
如果我有一个具有静态 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;
正如您在上面第一次看到的那样,我使用类内初始化程序初始化了PI_,然后我在没有任何初始化程序的情况下在类外定义了它。
在第二个中,我只是在没有初始化器的类中声明它,并在带有初始化器的类外部定义它。
- 哪种方法最好?
- 只要我提供了类内初始化器,在类外定义
PI_是否是多余的? 我可以说为 const 静态数据成员提供类内初始化程序被视为“定义”而不是“声明”吗?
-
也在“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.*”
但我试过了,在课外没有定义就工作了?!!!
谢谢!
【问题讨论】:
-
对于您展示的特定情况,选择基于编码风格,即它完全是任意和主观的。在某些情况下,外部定义是必需的,例如成员的类型在类定义中不完整。如果成员是私有的,则在类定义中可能不显示其初始化程序(这意味着 - 例如 - 在源文件中定义该成员,而不是在定义类的头文件中,因此成员初始化类的用户看不到)。