Sometimes, when using polymorphism, we want to use the parent class pointer to clone the corresponding subclass, but these parent class pointers are externally passed to the user. That is to say, the user does not know the corresponding subclass. In this case, if you can clone yourself? The following code demonstrates a simple usage method, hoping to give readers some inspiration.
The icloneable class is the key. Its clone method can clone itself. Therefore, if the subclass can be cloned, you must implement the icloneable class.
# Include <iostream>
# Include <time. h>
Using namespace STD;
Class icloneable
{
Public:
Virtual ~ Icloneable (){}
Virtual icloneable * clone () = 0;
};
Class IBASE: Public icloneable
{
Public:
Virtual ~ IBASE (){}
Virtual void who () = 0;
};
Class cwyq: Public IBASE
{
Public:
Virtual ~ Cwyq (){}
Virtual void who ()
{
Cout <"I am cwyq" <Endl;
}
Virtual icloneable * clone ()
{
Return new cwyq;
}
};
Class CWT: Public IBASE
{
Public:
Virtual ~ CWT (){}
Virtual void who ()
{
Cout <"I am CWT" <Endl;
}
Virtual icloneable * clone ()
{
Return new CWT;
}
};
Class czj: Public IBASE
{
Public:
Virtual ~ Czj (){}
Virtual void who ()
{
Cout <"I am czj" <Endl;
}
Virtual icloneable * clone ()
{
Return new czj;
}
};
Int main (void)
{
IBase * base [6];
Int I;
Memset (base, 0, sizeof (base ));
For (I = 0; I <3 ;)
{
// Srand (unsigned) Time (null ));
Int idx = rand () % 3;
If (base [idx] = NULL)
{
Switch (RAND () % 3)
{
Case 0:
Base [idx] = new cwyq;
Break;
Case 1:
Base [idx] = new CWT;
Break;
Case 2:
Base [idx] = new czj;
Break;
}
++ I;
} // End if (base [idx] = NUL)
}
For (I = 0; I <3; ++ I)
{
Base [I + 3] = static_cast <IBASE *> (base [I]-> clone ());
}
For (I = 0; I <6; ++ I)
{
Base [I]-> who ();
}
For (I = 0; I <6; ++ I)
{
If (base [I]! = NULL)
Delete base [I];
}
Return 0;
}