# Include <iostream>
# Include <vector>
# Include <iterator>
Using namespace STD;
Class cbase
{
Public:
Virtual void FN ()
{
;
}
Virtual void add (cbase B)
{
}
Virtual void add (cbase * pb)
{
}
Cbase (const cbase & B)
{
: Memcpy (void *) This, (void *) & B, sizeof (cbase ));
}
Cbase & operator = (const cbase & B)
{
: Memcpy (void *) This, (void *) & B, sizeof (cbase ));
Return * this;
}
Cbase ()
{
}
};
Class cpart: Public cbase
{
Public:
Void FN ()
{
Cout <"P: FN" <Endl;
}
};
Class ccom: Public cbase
{
Public:
Void FN ()
{
Cout <"com: FN" <Endl;
Vector <cbase >:: iterator ITB, ite;
ITB = This-> m_vb.begin ();
ITE = This-> m_vb.end ();//
For (; ITB! = Ite; ++ ITB)
(* ITB). FN ();
}
Void add (cbase B)
{
M_vb.push_back (B );
}
Virtual void add (cbase * pb)
{
M_pvb.push_back (PB );
}
Protected:
Vector <cbase> m_vb ;//
};
Int main (INT argc, char * argv [])
{
Cpart P1, P2, P3, P4;
Ccom C1, C2;
Cbase * pb = & P1;
Pb-> FN ();
PB = & C1;
Pb-> Add (P1 );
Pb-> Add (P2 );
Pb-> Add (P3 );
Pb-> FN ();
Return 0;
}
Output:
P: FN
COM: FN
P: FN
P: FN
P: FN
// Tool used: vc6
We force modify the pvtbl of the object (that is, the pointer to the vtable ). So even the object can be used to achieve polymorphism ,,
But don't forget platform relevance.
In addition, we usually do not modify pvtbl !!