【问题标题】:How to keep static const variable as a member of a class如何将静态 const 变量保留为类的成员
【发布时间】:2010-09-13 07:57:14
【问题描述】:

我想保留一个静态 const 变量作为类的成员。 是否可以保留以及如何初始化该变量。

有人这样说帮助了

 QString <ClassName>::ALARM_ERROR_IMAGE = "error.png";

Initilizing value for a const data

我试过这样

在 CPP 课上我写了

static  QString ALARM_WARNING_IMAGE ;

在构造函数中我写

ALARM_WARNING_IMAGE        = "warning.png";

但不工作...请提供一些提示帮助

【问题讨论】:

    标签: c++ visual-c++ qt qt4


    【解决方案1】:

    在源文件中的任何函数外写:

    const QString ClassName::ALARM_WARNING_IMAGE = "warning.png";
    

    这种结构也有效:

    const QString ClassName::ALARM_WARNING_IMAGE("warning.png");
    

    标题:

    class ClassName {
      static const QString ALARM_WARNING_IMAGE;
    };
    

    另外,不要在构造函数中写任何东西。这将在每次实例化 ClassName 时初始化静态变量。这不起作用,因为变量是 const 并且可以说是个坏主意。 consts 只能在声明期间设置一次。

    【讨论】:

      【解决方案2】:

      基本思路如下:

      struct myclass{
       //myclass() : x(2){}      // Not OK for both x and d
       //myclass(){x = 2;}       // Not OK for both x and d
       static const int x = 2;   // OK, but definition still required in namespace scope
                                     // static integral data members only can be initialized
                                     // in class definition
           static const double d;    // declaration, needs definition in namespace scope,
                                     // as double is not an integral type, and so is
                                     // QSTRING.
           //static const QString var; // non integral type
      };
      
      const int myclass::x;             // definition
      const double myclass::d = 2.2;    // OK, definition
      // const QString myclass::var = "some.png";
      
      int main(){
      }
      

      【讨论】:

      • 有什么理由评论var?这似乎暗示它无效,当它有效时。
      • @Mike Seymour:因为我没有 QString 定义。
      【解决方案3】:

      试试:

      QString ClassName::ALARM_WARNING_IMAGE = "warning.png";

      【讨论】:

      • 任何需要在C++类中声明
      • 如果你让它保持不变,你必须同时标记 declaration (在类中)和 definition (这就是这个答案所显示的) 作为const.
      • 看我的回答。它应该足够详细,以了解它是如何工作的
      【解决方案4】:

      只允许在类或结构中初始化 const 静态整数数据成员。

      【讨论】:

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