static constant members for array size

前端 未结 5 861
一生所求
一生所求 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:13

    Static const members of simple type are a exception to that rule, so you latter code is correct.

    This exception is a fairly modern one (from C++98, but not implemented by every compiler until a few years later) so many old-fashioned teachers are not yet aware of it. They prefer the idiom:

    class MyClass
    {
    public:
       enum { cTotalCars = 5 };
    
    private:
        int m_Cars[cTotalCars];
    };
    

    That behaves exactly the same, but makes little sense nowadays.

提交回复
热议问题