【问题标题】:static member vs static const member instantiation - what's the difference? [duplicate]静态成员与静态 const 成员实例化 - 有什么区别? [复制]
【发布时间】:2016-02-24 14:18:41
【问题描述】:

这两个成员在初始化和实例化问题上到底有什么区别?:

class Test {
    // ctor, dtor, ... here
private:
    static int m_test = 0;             // error - non-const ...
    static const int m_const_test = 0; // working - const ...
};

为什么非常量成员的初始化无效? 什么时候会实例化两个变量(假设没有 init 的非 const 成员!)?

编辑:即使这个问题的很大一部分可以叠加到提到的帖子中,我认为这些条目中并没有回答我问题的每个部分。

BR,金枪鱼

【问题讨论】:

标签: c++ static


【解决方案1】:

如果多个编译单元包含您的类定义,那么您的静态int m_test = 0 应该放在哪个编译单元中?对于const static ... 来说没关系,因为它是 const。

【讨论】:

    【解决方案2】:

    m_const_test 被声明为 const 不能更改。

    所以,使用 m_const_test 可以节省一点时间,但不如 m_test 灵活。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-20
      • 2015-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      相关资源
      最近更新 更多