【问题标题】:How to have static constants in a cpp class?如何在 cpp 类中有静态常量?
【发布时间】:2012-03-29 22:55:03
【问题描述】:

我是从一个沉重的 java 背景进入 c++ 的。

如何将常量与类关联? 如果是 Java,它会是这样的

public class Example{
    public static final int CONSTANT = 0;
}

public static void main (String[] args){
    System.out.println(Example.CONSTANT);
}

结果将只是 0。

到目前为止,我已经想到了在 c++ 中:

class Example{
    const int LEVEL_INF;
}

这是正确的吗?
即使通过 ISO 98?

【问题讨论】:

    标签: c++ class static


    【解决方案1】:
    class Example{
        const int LEVEL_INF;
    };
    

    不是每个类,而是每个实例。您需要将其设为静态:

    class Example{
        static const int LEVEL_INF;
    };
    

    静态 const 整数类型的优点是可以在类内部初始化它们,不一定在外部:

    class Example{
        static const int LEVEL_INF = 1337;
    };
    

    另外,如果您想公开访问它,请添加 public

    编辑:根据@ildjarn 的建议,在类之外对其进行初始化:

    //header.h
    class Example{
        static const int LEVEL_INF;
    };
    
    //implementation.cpp
    
    const int Example::LEVEL_INF = 1337;
    

    【讨论】:

    • 这只会在他需要 ODR 使用 LEVEL_INF 之前很好,此时它需要一个类外定义,所以我认为这是值得的在这里演示如何做到这一点。
    • iso 98 标准对此没有影响?
    • @kotoko:C++98 标准与什么相对?这是有效的 C++98、C++03 和 C++11。
    【解决方案2】:

    为了完整起见,这里是static const以外的另一种方法:

    class Example
    {
        // Anonymous enum
        enum { LEVEL_INF = 0; };
    };
    

    【讨论】:

      【解决方案3】:

      只要它是一个整数常量,比如int,你就可以像在Java中那样做

      class Example {
      public:
          static const int LEVEL_INF = 0;
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-25
        • 1970-01-01
        • 1970-01-01
        • 2014-12-25
        • 1970-01-01
        • 1970-01-01
        • 2010-09-09
        • 2015-12-15
        相关资源
        最近更新 更多