There are the following classes:
class base{public:base(char* pStr){m_pStr = pStr;cout << pStr << " Constructor!" << endl;}~base(){cout << m_pStr << " Destructor!" << endl;}void fund(char* pStr){if (pStr != NULL){static base b(pStr);}}void fund2(){static base e("e");}private:char* m_pStr;};base glb("global");
1. The following call methods are available:
int main(){base loc("local");return 0;}
What is the output?
Answer:
Global Constructor!
Local Constructor!
Local Destructor!
Global Destructor!
Note that the static variable in the function is not initialized because the function is not called ~
Next, we will use the following code:
int main(){base d("d");int i;cin >> i;if (i == 0){d.fund(NULL);d.fund("R1");d.fund2();}else{d.fund2();d.fund("R2");}return 0;}
When the user inputs 0
Global Constructor!
Local Constructor!
R1 Constructor!
E Constructor!
Local Destructor!
E Destructor!
R1 Destructor!
Global Destructor!
When the user input is not 0
Global Constructor!
Local Constructor!
E Constructor!
R2 Constructor!
Local Destructor!
R2 Destructor!
E Destructor!
Global Destructor!
It can be seen that static variables can be executed only when the user enters the initialization Code for the first time, and the execution process can be changed according to user input, you can even follow the correct "create first and then destroy!