1. class member is const type
2. Class members are reference types
#include <iostream>using namespacestd;classa{ Public: A (int&v): I (v), P (v), J (v) {}voidPrint_val () {cout <<"Hello:"<< I <<" "<< J <<Endl;}Private: Const intI//class member is const type intp; int&j;//class member is a reference type};intMainintargcChar**argv) { intPP = $; A b (PP); B.print_val ();}
Operation Result:
The reason
A const object or reference can only be initialized but cannot be assigned a value. The function body of a constructor can only be assigned values rather than initializations, so the only chance to initialize a const object or reference is in the initialization list before the body of the constructor function.
From Scratch called initialization, initialization (call copy constructor) creates new object, assignment (call assignment operator) does not create new object, but assigns value to existing object .
3. Class Members are class types that do not have a default constructor
1#include <iostream>2 using namespacestd;3 4 classBase5 {6 Public:7Base (inta): Val (a) {}8 Private:9 intVal;Ten }; One A classA - { - Public: theAintv): P (v), B (v) {} - voidPrint_val () {cout <<"Hello:"<< P <<Endl;} - Private: - intp; +Base b;//class member is a class without a default constructor - }; + A intMainintargcChar**argv) at { - intPP = $; - A B (pp); - b.print_val (); -}
Operation Result:
The same reason is that every member of a class member is initialized when the object is created
4. If the class has an inheritance relationship, the derived class must call the constructor of the base class in its initialization list
1#include <iostream>2 using namespacestd;3 4 classBase5 {6 Public:7Base (inta): Val (a) {}8 Private:9 intVal;Ten }; One A classA: PublicBase - { - Public: theAintV): P (v), Base (v) {}//Class A inherits from class base and needs to call the constructor of base in its initialization list - voidPrint_val () {cout <<"Hello:"<< P <<Endl;} - Private: - intp; + }; - + intMainintargcChar**argv) A { at intPP = $; - A B (pp); - b.print_val (); -}
Operation Result:
Above.
In the "Go" constructor, there are several cases where member variables must be initialized by initializing the list