C++: Initialization of inherited field

前端 未结 4 1196
长发绾君心
长发绾君心 2020-12-02 01:36

I\'ve a question about initialization of inherited members in constructor of derived class. Example code:

class A
    {
public:
    int m_int;
    };

class          


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 02:27

    What you want is this:

    class A{
    public:
        A() : m_int(0);
        int m_int;
    };
    

    so that m_int is initialized in the correct place.

    Edit:

    From a comment above, the reason the compiler complains when you try to initialize the m_int variable in B is that it's already been initialized by the constructor of A. That is, you can't re-initialize something, only reassign. So, you can reassign like Ben Jackson stated above or you can initialize in the proper place.

提交回复
热议问题