The default constructor to initialize its static members can it?

Introduction: We know that when you call the constructor, the constructor automatically initializes its non-static members, such as:

class NotStaticMember
{
public:
	NotStaticMember(){ cout << "NotStaticMember() is called" << endl; }
	~NotStaticMember(){ cout << "~NotStaticMember() is called" << endl; }
};

class CanIniNotStaticMember
{
public:
	CanIniNotStaticMember() = default;
	~CanIniNotStaticMember() = default;
private:
	NotStaticMember nsm;
};

int main()
{
	CanIniNotStaticMember cinsm;
}

  

result:

 

 

Explore: Well constructor to initialize static member can default it? An experiment at a glance:

 

case1: the function is not defined outside nsm, not defined in the main function of example StaticMember

class StaticMember
{
public:
	StaticMember(){ cout << "StaticMember() is called" << endl; }
	~StaticMember(){ cout << "~StaticMember() is called" << endl; }
};

class CanIniStaticMember
{
public:
	CanIniStaticMember() = default;
	~CanIniStaticMember() = default;
private:
	static StaticMember sm;
};

int main()
{
    
}

  

result:

 

 Conclusion: During the program is compiled and not automatically initialize static class members.

 

case2: function is not defined outside nsm, defined in the examples StaticMember main function

int main()
{
	CanIniStaticMember cism;
}

  

result:

 

 Conclusion: The constructor does not automatically initialize static member.

 

case3: the function defined outside sm, is not defined in the examples CanIniStaticMember main function

StaticMember CanIniStaticMember::sm;

int main()
{
	
}

  

result:

 

 Conclusion: The class with static members only if they are related to the manual initialize static member, regardless of whether the object class is created. That is: If you do not manually initialize static member class, the static member will never be initialized.

Guess you like

Origin www.cnblogs.com/XiaoXiaoShuai-/p/11504889.html