Singleton mode: Only one object can be generated for each class.
# Include <stdio. h>
Class
{
PRIVATE:
Int ID;
A () {} // place the constructor in private: the objective is to not directly allocate space definition objects on the stack outside the class.
Public:
Static A * PT;
Static A * instance ()
{
If (Pt = NULL) // note that it is a double equal sign, and it seems that it is difficult to use null in C ++.
{
PT = new;
Return pt;
}
Else
Return pt;
}
~ A ()
{
Delete pt; // because the heap space is opened, delete is used for release.
}
Void id_set (int x)
{
Id = X;
}
Void id_get ()
{
Printf ("% d", ID );
}
};
A * A: Pt = NULL; // static member variables can only be initialized outside the class.
Int main ()
{
// This class cannot allocate objects on the stack. Objects can only be allocated on the stack using the new function interface provided in the class.
A * PPT = A: instance ();
PPT-> id_set (10 );
PPT-> id_get ();
A * ppt1 = A: instance ();
Ppt1-> id_get ();
Ppt1-> id_set (5 );
PPT-> id_get ();
Return 0; // automatically call the Destructor at the end of the Function ~ A ();
}
The output is 10105
The ppt and ppt1 point to the same object.