static constant members for array size

前端 未结 5 800
一生所求
一生所求 2021-02-09 15:54

MyClass.h

class MyClass
{
public:

static const int cTotalCars;

private:

int m_Cars[cTotalCars];
};

MyClass.cpp

5条回答
  •  离开以前
    2021-02-09 16:07

    The above will work, but I am told that I should always define static members in the CPP file, outside the class definition. What can I do?

    Well, what you have been suggested to do: define the static members in the CPP. Note that in the code above the static member is not defined even if the value is stated. The proper final code would look like:

    // .h (ignoring all but the static member)
    class MyClass {
       static const int cTotalCars = 5;        // declaration and initialization
    };
    // .cpp
    static const int MyClass::cTotalCars;      // definition (cannot have value!)
    

    The definition in the .cpp file is what actually reserves the space for the variable when used as an lvalue. For a simple test that verifies that without that line the variable is not defined you can do:

    void f( const int & x ) {}
    int main() {
       f( MyClass::cTotalCars );
    }
    

    Without the line in the .cpp file the code above will trigger a linker error pointing to the missing definition of MyClass::cTotalCars. The problem with the code is that it uses the static const member (by the definition of use in the standard), and that requires the member to be defined. While the case of using the constant to define the array size does not constitute use.

提交回复
热议问题