C++ defining a constant member variable inside class constructor

前端 未结 4 936
猫巷女王i
猫巷女王i 2021-02-05 10:35

Usually when you have a constant private member variable in your class, which only has a getter but no setter, it would look something like this:

// Example.h
cl         


        
4条回答
  •  无人共我
    2021-02-05 11:03

    You have two basic options. One is to use the conditional operator, which is fine for simple conditions like yours:

    Example::Example(const std::vector &myVec)
      : m_value( myVec.size() ? myVec.size() + 1 : -1)
    {}
    

    For more complex things, you can delegate the computation to a member function. Be careful not to call virtual member functions inside it, as it will be called during construction. It's safest to make it static:

    class Example
    {
      Example(const std::vector &myVec)
        : m_value(initialValue(myVec))
      {}
    
      static int initialValue(const std::vector &myVec)
      {
        if (myVec.size()) {
          return myVec.size() + 1;
        } else {
          return -1;
        }
      }
    };
    

    The latter works with out-of-class definitions as well, of course. I've placed them in-class to conserve space & typing.

提交回复
热议问题