views:

87

answers:

4

Hi,

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";

http://stackoverflow.com/questions/3698446/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

A: 

Try:

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

Rob
Any need to declare inside C++ class
I want to make it constant... Without giving constant its working...
If you make it constant, you have to mark BOTH the *declaration* (in the class) and the *definition* (which is what this answer shows) as `const`.
Ben Voigt
see my answer. it should be detailed enough to see how it's working
Ronny
A: 

Only const static integral data members are allowed to initialized inside a class or struct.

Santosh kumar
+2  A: 

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(){
}
Chubsdad
Any reason for commenting out `var`? That seems to imply that it's not valid, when it is.
Mike Seymour
@Mike Seymour: Because I don't have QString definition with me.
Chubsdad
+1  A: 

Outside of any function in the source file write:

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

Header:

class ClassName {
  static const QString ALARM_WARNING_IMAGE;
};

Also, don't write anything in the constructor. This would initialize the static variable everytime ClassName is instantiated ... which does not work, because the variable is const ... bad idea so to speak. consts can only be set once during declaration.

Ronny
Thanks a lot... Its working