This problem is caused by an interview question: how to initialize the referenced member variable?
The answer is not very definite, so I will study this question.
1. Common variables: assign values in constructors without considering the efficiency. For efficiency, you can perform this operation in the initialization list of the constructor.
Class ca
{
Public:
Int data;
......
Public:
CA ();
......
};
CA: Ca (): Data (0 )//...... #1 ...... Initialize the list
{
// Data = 0 ;//...... #1 ...... Assignment Method
};
2. Static static variables:
Static variables belong to all classes but not class objects. Therefore, no matter how many objects the class is instantiated, this variable has only one. In terms of this nature, it is somewhat similar to the uniqueness of global variables.
Class ca
{
Public:
Static int sum;
......
Public:
CA ();
......
};
Int CA: Sum = 0 ;//...... #2 ...... Class initialization
3. Const constant variable:
The const constant must be initialized upon declaration. Therefore, Initialization is required when a variable is created. It is generally carried out in the initialization list of the constructor.
Class ca
{
Public:
Const int Max;
......
Public:
CA ();
......
};
CA: Ca (): max (100)
{
......
}
4. Reference variables:
The referenced variable is similar to the const variable. It must be initialized at the time of creation. Also in the initialization list. Note that the reference type is used.
Class ca
{
Public:
Int Init;
Int & Counter;
......
Public:
CA ();
......
};
CA: Ca (): Counter (& init)
{
......
}
5. Const static integral variable:
C ++ is privileged for const, static, and integer variables. It can be initialized directly in the class definition. Short works, but float does not.
Class ca
{
Public:
// Static const float fmin = 0.0; // only static const integral data members can be initialized within a class
Const static int Nmin = 0;
......
Public:
......
};
To sum up, there are four possible initialization conditions:
1. In the class definition, only the const and static and integral variables are involved.
2. In the class constructor initialization list, including the const object and reference object.
3. initialized outside the class definition, including static variables. Because it is a unique variable of the class.
4. Common variables can be assigned within the constructor. Of course, this is inefficient.