Qt: default value of a variable in a class

When creating my own class in Qt, I would like my variables in the class to have a standard value / default value if I didn't set them to anything. It would be ideal if it were possible to install in the h file, so I do not need to do this in every instance of the method of my class. You can see what I want to do in the code below. In the example, myBool will be false and myInt will be 0 when the object was created. Is this even possible?

In myclass.h:

class MyClass
{
    Q_OBJECT

public:
MyClass();
   ~MyClass();
    bool myBool = false; //I want to set myBool and myInt to a default/standard value
    int myInt = 0; 
};
+3
source share
3 answers

Qt ++, - .

MyClass::MyClass() : myBool(false), myInt(0)
{
}
+6

, , , ++. ++ 0x , :

class MyClass
{
    Q_OBJECT

public:
    MyClass() : myBool(false), myInt(0) { }
   ~MyClass();
    bool myBool;
    int myInt;
};
+5

!

, ++, .

, MyClass.

!!!

, : , .

, :

void foo()
{
   bool b ;            // WRONG : Not initialized
   Variable<bool> bb ; // Ok : Initialized to false

   int i ;             // WRONG : Not initialized
   Variable<int> ii ;  // Ok : Initialized to 0

   // etc.
}

, , bool:

template<typename T>
class Variable
{
   T value_ ;

   public :
      Variable() ;
      Variable(const T & rhs) ;
      Variable(const Variable & rhs) ;

      Variable & operator = (const T & rhs) ;
      Variable & operator = (const Variable & rhs) ;

      operator T() const ;

      // define all other desired operators here
} ;

, , . :

template<typename T>
inline Variable<T>::Variable()
   : value_(0)
{
}

// For the fun, I want all booleans initialized to true !
template<>
inline Variable<bool>::Variable()
   : value_(true)
{
}

// For the fun, I want all doubles initialized to PI !
template<>
inline Variable<double>::Variable()
   : value_(3.1415)
{
}

// etc.

template<typename T>
inline Variable<T>::operator T() const
{
   return value_ ;
}

// etc.

, , . , . ( ), .

, , , .

, - ++.

:

class MyClass
{
   Q_OBJECT

public:
   MyClass();
   ~MyClass();

   Variable<bool> myBool ;  // it will be set to false, as defined
   Variable<int> myInt ; // it will be set to 0, as defined
};

:

void foo()
{
   MyObject o ;
   o.myBool = true ;

   if(o.myInt == 0)
   {
      ++o.myInt ;
   }
}

, - , "release" .

+2
source

Source: https://habr.com/ru/post/1737926/


All Articles