The initialization of classes in C + + typically consists of four parts:
1. Constructor initialization list
2. Assigning values in the constructor body
3. Class external initialization
4. Assigning values directly when declaring a class
For internal data types (Char,int,float ...), constructor initialization lists and constructors are assigned in the body, basically not much difference, the efficiency difference is not small, but the two cannot coexist:
classstudent{ Public: Student (Char*name,intAge)://a list of initializationM_name (name), M_age (age) {}
Student (char *NameintAge//In- body initialization of B function{m_name=name; M_age=Age ; }Private: Char*m_name; intm_age;};
For class types, it is preferable to use the initialization list method, which uses the initialization list relative to the constructor method to call the default constructor one less time, which is more efficient for data-intensive classes;
* * Initialize list mode: All class non-static data members can be initialized here, and the order in which member variables are initialized is in the order defined by the header file, but the class static data members cannot be initialized here;
* * Constructor Body Internal mode:
For class non-static members, const type, reference type, and no default constructor test members cannot be initialized here;
[1] constant member, because constants can only initialize can not be assigned value, so must be placed in the initialization list
[2] Reference type, the reference must be initialized at the time of definition, and cannot be re-assigned, so it is also written in the initialization list
[3] There is no default constructor for the class type, because using an initialization list can be initialized without calling the default constructor, but instead directly by invoking the copy constructor class.
For a class static member, you can modify a modifiable static member here, but the static member must already be initialized outside of the class;
* * Class external initialization: a static const int data member can be initialized outside the class, or it can be initialized at the declaration of a class member, and other static data members must be initialized outside of the class;
* * Declared in class: like static const int data member can be initialized at the declaration of the class member;
C + + constructor initialization list and assignment