C++ - initializing variables in header vs with constructor

前端 未结 7 912
盖世英雄少女心
盖世英雄少女心 2021-01-31 02:00

Regarding the following, are there any reasons to do one over the other or are they roughly equivalent?

class Something
{
    int m_a = 0;
};

v

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-31 02:43

    The first form is more convenient if you have more than one constructor (and want them all to initialise the member in the same way), or if you don't otherwise need to write a constructor.

    The second is required if the initialiser depends on constructor arguments, or is otherwise too complicated for in-class initialisation; and might be better if the constructor is complicated, to keep all the initialisation in one place. (And it's also needed if you have to support pre-C++11 compilers.)

提交回复
热议问题