首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >是用类内初始化器初始化静态const数据成员,还是在类外定义中初始化静态const数据成员?

是用类内初始化器初始化静态const数据成员,还是在类外定义中初始化静态const数据成员?
EN

Stack Overflow用户
提问于 2019-07-10 23:38:39
回答 1查看 44关注 0票数 0

如果我有一个具有静态const数据成员的类,那么初始化它的最佳方法是什么:

代码语言:javascript
运行
复制
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++引物第五版: "*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.*

但是我试过了,在课堂之外没有定义地工作?!

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2019-07-10 23:46:24

您最好只使用constexpr,这意味着您可以将其全部保存在类定义中。

代码语言:javascript
运行
复制
class Circle{
public:
    //...
private:
    static constexpr double PI_ = 3.14; // 1
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56979888

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档