1. What is a member initialization list
#include <iostream>#include<string>using namespacestd;classweapon{Private: stringname; Const stringtype; Const stringmodel; Public: Weapon (stringNamestringTypestringmodel) : Name (name), type (type), model (model) {Name="Cloud"; } stringGetProfile () {return "Name:"+ name +"\ntype:"+ Type +"\nmodel:"+model; }};intMainvoid) {Weapon Weapon ("Comet","Carbine","Rifle"); cout<< Weapon.getprofile () <<Endl; Cin.Get(); return 0;}
The red part of the code above is the member initialization list
Notice that the name of the constructor is "Cloud"; The value of the initialized list is overridden by the
2. Why a member initialization list is required
Both type and model are constants that can be initialized but cannot be assigned, and an error will be made if an assignment such as type = "XXX" is attempted in the function body of the constructor. Conceptually, before entering the function body of a constructor, the object has been created, so initialization must be done before the object is created, so C + + has invented the initialization list, which is considered to be initialization.
Please note: 1. This format can only be used for constructors;
2. You must use this method to initialize a non-static const data member (static const data is not part of the object so it cannot be initialized in the constructor);
3. Reference data members must be initialized in this format (this is because the reference is similar to the const data and can only be initialized at creation time)
List of C + + member initialization