C + + stipulates that the initialization action of a member variable of an object occurs before entering the constructor body.
#include <iostream>
#include <string>
using namespace std;
Class STU
{public
:/
*
name is initialization, sex and age are assigned */
STU (string _name,string _sex,int _age): Name ( _name)
{
sex=_sex;
age=_age;
}
void Printstu ()
{
cout<< "name:" <<name<<endl<< "Gender:" <<sex<<endl< < "Age:" <<age<<endl;
}
Private:
string name;
string sex;
int age;
};
int main ()
{
STU s ("Chen", "male", +);
S.printstu ();
return 0;
}
In the above program, name is initialized in the initialization list, and sex and age are assigned values in the constructor body.
Name uses a copy construct one step, and sex calls the default constructor initialization before calling the copy operator. Increases the overhead.
For built-in types, such as int age, there is little difference between assignment and initialization.
Therefore, the initialization should be done in the member variable initialization list whenever possible.
initialization Order of member initial value columns
#include <iostream>
#include <string>
using namespace std;
Class STU
{public
:
STU (int _age): "Money", Age (_age)
{
}
void Printstu ()
{
cout<< "Age:" <<age<<endl<< "Money:" <<money<<endl;
}
Private:
int age;
int money;
};
int main ()
{
STU s (+);
S.printstu ();
return 0;
}
A sudden look, as if this initialization list has a problem: first with age to initialize money, and then initialize the age, it is not money using a wrong value to initialize.
In fact, the initialization order of the member initial columns depends on the order in which the member variables are declared.
Private
int age;
int money;
Declares the age, declaring money, so there is no problem with dirty initialization.
However, it is best to keep the initialization list consistent with the order of declarations.