C++ defining a constant member variable inside class constructor

前端 未结 4 931
猫巷女王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 10:55

    First, the variable is defined in the class definition, not in the constructor. It's initialized in the constructor.

    Second, the way to do that is just like what your constructor currently does: store the value in it from the initializer list:

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

提交回复
热议问题