static variable in the class declaration or definition?

后端 未结 4 1674
夕颜
夕颜 2020-12-01 21:07

I am new to C++.
I have a class like this:

class CodeTest
{
private:
    static const int TOTAL=100;
};

Is TOTAL a dec

4条回答
  •  情歌与酒
    2020-12-01 22:07

    The declaration in an implementation file outside of the header is required because otherwise every translation unit that includes this header would define its own object (that is, its own storage for the variable).

    This would violate the One Definition Rule. A consequence would be e.g. that if the variable was changed in one translation unit, this change would be invisible to other translation units. Now, this isn’t that relevant since the variable is constant. However, taking its address would also yield different pointers in different translation units.

提交回复
热议问题