Sometimes we need to define a class in our program, this class can only create a valid instance, in many companies recruitment written questions, also often encounter such a topic. There are a lot of posts on the Internet, but they are very general, or some of the procedures in the post is somewhat wrong. Here to share with you my understanding of this issue, C + +.
It is recommended that you use the first method to customize the number of class object limits.
The first method is to create a static variable count in the class to limit the number of instances that can be created. The complete program fragment is as follows, I try to add all the comments in the program:
#include <iostream>
class Singleclass
{public
:
static singleclass* Getsingleclass () // Static member function
{if
(Count > 0)
//If Count is greater than 0, then call new to create a class pointer, and count count minus 1, otherwise return null
{
count--;
return new Singleclass ();
}
else
{return
NULL;
}
}
Private:
Singleclass () {};
static int Count; The static member variable count is not allowed to initialize in the class. Defined as const can be initialized in this, but not changed, not suitable for use in this
};
int singleclass::count = 1; Initialization of Count, you can set limits on the number of instances you create
int main ()
{
singleclass* test; class instances can only be created by defining class pointers
test = Singleclass::getsingleclass ();
return 0;
}
The first time the above program calls the Getsingleclass function, you get a correct class object pointer. If the Getsingleclass function is called the second time, a null is obtained. The static int count variable cannot be initialized in a class and needs to be initialized outside of the class.
The second method, which creates a static class pointer variable Psinclass in the class, is initialized to null, and when a class instance is successfully created, Psinclass is no longer null, and if Psinclass is not NULL, the class object cannot be created. The complete program fragment is as follows:
#include <iostream>
class Singleclass
{public
:
static singleclass* Getsingleclass () // Static member function
{if
(Psinclass = null)
//If Psinclass is null, call new to create a class pointer, otherwise return NULL
{
psinclass = new Singleclass ();
return psinclass;
}
else
{return
NULL;
}
}
Private:
Singleclass () {};
Static singleclass* Psinclass; Static member variable Psinclass, not allowed to initialize in class. Defined as const can be initialized in this, but not changed, not suitable for use in this
};
singleclass* singleclass::p sinclass = NULL; Psinclass initialization
int main ()
{
singleclass* test; class instances can only be created by defining class pointers
test = Singleclass::getsingleclass ();
return 0;
}
The above introduces two simple ways to limit the number of instances of class, personal opinion, there is a bad place please understand, what better advice, reply AH ~ ~ ~