Static member of a class in the same class

Suppose we have a class like

class Egg
{
static Egg e;
int i;
Egg(int ii):i(ii) {}
Egg(const Egg &);    //Prevents copy-constructor to be called
public:
static Egg* instance() {return &e}
};

Egg Egg::e(47);

This code ensures that we cannot create any object, but we can only use a static object. But how can we declare a static object of the same class in the class.

And one more thing, since e is a static object, and static objects can only call static member functions, therefore, as a constructor, it can be called here for a static object e, and its constructors are private.

+5
source share
2 answers

But how can we declare a static object of the same class in the class.

A static - . , - static , , (Class::var var) protected private .

, e , -

, static static. static static ( ).

e

, static.

++. static , private .

, ++ : - (other ):

 class Test {
 private:
      int i;
 public:
      Test(const Test &other)
      : i(other.i)
      {}
 };
+6

.

, Egg e , . e , (- " Egg e " ).

, e - , -, e.

. - . static Egg e - Egg, , .

.

. static Egg e Egg, . e , , .

, , , :

static Egg* instance() {return &e;}
+2
source

All Articles