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
To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.
A static member variable: • Belongs to the whole class, and there is only one of it, regardless of the number of objects. Must be defined and initialized outside of any function, like a global variable. It can be accessed by any member function of the class. Normally, it is accessed with the class scope operator.
A static data member can be of any type except for void or void qualified with const or volatile. You cannot declare a static data member as mutable.
Avoid using the const keyword with member variables of a class or struct type. For a class type, if a piece of data is not supposed to change after being initialized, enforce this by design of the public API, not via the `const` key word. For a struct which is a "dumb aggregate", it isn't appropriate to use `const`.
Outside of any function in the source file write:
const QString ClassName::ALARM_WARNING_IMAGE = "warning.png";
This construction also works:
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. This does not work, because the variable is const and a bad idea so to speak. consts can only be set once during declaration.
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(){
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With