Search code examples
c++visual-c++qtqt4

How to keep static const variable as a member of a class


I want to keep a static const variable as a member of class. Is it possible to keep and how can i initilize that variable.

Some body helped by saying this

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

Initilizing value for a const data

I tried like this

in CPP class i write

static  QString ALARM_WARNING_IMAGE ;

In constructor i write

ALARM_WARNING_IMAGE        = "warning.png";

But not working... Please help by giving some hints


Solution

  • Here is the basic idea:

    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(){
    }