Why can't I initialize my static data member in my constructor

后端 未结 5 1939
無奈伤痛
無奈伤痛 2020-12-15 05:28

I read the answer in parashift but I need bit details as to why compiler won\'t allow to define static member variable in constructor.

5条回答
  •  青春惊慌失措
    2020-12-15 06:21

    I presume you're referring to using it in an initialization list to a constructor. A static data member is shared among all instances of the class. It can be initialized once (by definition of initialization), so it wouldn't make sense to initialize it for each instance.

    You could, however, assign it a value (or mutate the existing value) in the constructor body. Or if the data member is a constant, you can initialize it statically outside of the constructor.

提交回复
热议问题