Tagged with: C + +
In C + +, there are 4 scenarios in which member variables must be initialized using the argument list of the constructor:
(1) The member variable type is const int m_ndata;
Class Test{private:const int m_ndata;public:test (): M_ndata (120) {}};
(2) A reference variable in a class
Class Test {Private:int m_ndata; const int & m_ntest; Public:test (): M_ntest (m_ndata) {}//An initial reference-type variable with another member variable m_ndata};
(3) The class contains a second class as a member variable, and the contained class has a parameter constructor, no parameterless constructor
class a{int m_ndata; public:a (int A)//has a parameter constructor and does not explicitly declare an parameterless constructor {m_ndata = A; };}; The class b{Public:a c;//contains the classes A object as the current class member Variable B (): C (101) {}};
(4) Two classes have a secondary relationship, the parent class does not show the declared parameterless construction number, but declares that there is a parametric constructor
Class a{Public:int M_ndata; A (int a)//with a parameter constructor, without an explicitly declared parameterless constructor {m_ndata = A; };}; Class B:public A//Inherit parent class a{public:b (): A (101) {}//must initialize the parent class};
4 scenarios in C + + that must be initialized with a parameter list