【问题标题】:c++ class constant of its own class自己类的c++类常量
【发布时间】:2015-02-28 20:23:10
【问题描述】:

基本上,我想在类本身中声明一个类的常量:

class MyClass {
    int itsValue;
    public:
        MyClass( int anInt) : itsValue( anInt) {}
        static const MyClass CLASSCONST;
};

所以我可以这样访问它;

MyClass myVar = MyClass::CLASSCONST;

但我找不到初始化 MyClass::CLASSCONST 的方法。它应该在 MyClass 声明中初始化,但此时构造函数是未知的。任何人都知道这个窍门,或者在 c++ 中是不可能的。

【问题讨论】:

    标签: c++ class constants


    【解决方案1】:
    class MyClass {
        int itsValue;
        public:
            MyClass( int anInt) : itsValue( anInt) {}
            static const MyClass CLASSCONST;
    };
    
    const MyClass MyClass::CLASSCONST(42);
    

    【讨论】:

      【解决方案2】:

      Here 是一个在类外定义的工作示例。 类声明有一个 const static 成员,该成员在类外部初始化,因为它是静态成员且类型为非整数。所以类本身的初始化是不可能的。

      #include <iostream>
      
      class test
      {
          int member ;
      public:
          test(int m) : member{m} {}
      
          const static test ob ;
      
          friend std::ostream& operator<<(std::ostream& o, const test& t)
          {
              o << t.member ;
              return o;
          }
      };
      
      const test test::ob{2};
      
      int main()
      {
          std::cout << test::ob ;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多