How to clone yourself in Polymorphism

Source: Internet
Author: User
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;
}
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.