This question already has an answer here:
This code works fine as an implementation of Singleton pattern.
I want to understand Singleton *Singleton::obj = 0;
.
What is that doing and why is that important?
Please explain.
#include <stdio.h>
class Singleton
{
private:
static Singleton *obj;
Singleton()
{
obj = NULL;
}
unsigned int zero = 0;
public:
static Singleton * getObject()
{
if( obj == NULL )
obj = new Singleton();
else
printf( "\nMemory has already been allocated!\n" );
return obj;
}
void addToZero()
{
zero++;
printf( "\nzero has now become: %d\n", zero );
}
};
Singleton *Singleton::obj = 0;
int main()
{
Singleton *p = Singleton::getObject();
p->addToZero();
Singleton *p1 = Singleton::getObject();
p1->addToZero();
}
Aucun commentaire:
Enregistrer un commentaire