C++ - initializing variables in header vs with constructor

前端 未结 7 921
盖世英雄少女心
盖世英雄少女心 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:38

    class Something
    {
        int m_a = 0;
    };
    

    is equivalent to

    class Something
    {
        int m_a(0);
    };
    

    So, doing

    class Something
    {
        int m_a;// (0) is moved to the constructor
    public:
        Something(): m_a(0){}
    };
    

    yields a uniform syntax for initialization that requires or does not require run-time input.

    Personally I don't like the first form because it looks like an "declaration then assignment", which is complete misconception.

提交回复
热议问题