如果我有一个具有静态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_定义是否是多余的?*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.*“但是我试过了,在课堂之外没有定义地工作?!
谢谢!
发布于 2019-07-10 23:46:24
您最好只使用constexpr,这意味着您可以将其全部保存在类定义中。
class Circle{
public:
//...
private:
static constexpr double PI_ = 3.14; // 1
};https://stackoverflow.com/questions/56979888
复制相似问题