Rtti-pen questions

Source: Internet
Author: User
TTI
// A pen exam
// Evaluate the knowledge of rtti and identify runtime types
// You also need to enable the rtti function of the VC compiler.
// Select C ++ language for project/settings/C ++/catogory and you will see that option.
# Include < Iostream >
# Include < Typeinfo >
Using   Namespace STD;
Class   Base
{
Public :
Virtual   Void Funca () {cout <   " Base "   < Endl ;}
};
Class Derived: Public   Base
{
Public :
Virtual   Void Funcb () {cout <   " Derived "   < Endl ;}
};
// Requires that func be able to output the actual type of the form parameter. either of the following func can

//Funcc uses the dynamic_cast type conversion to identify the type.

// Dynamic_cast must be performed in hierarchy with virtual functions.
Void Funcc ( Base   * P)
{
Derived * DP = Dynamic_cast < Derived *> (P );
If (DP ! = Null)
DP -> Funcb ();
Else
P -> Funca ();
}

// Funcd uses the typeid Operator

Void Funcd ( Base   * P)
{
Derived * DP = NULL;
If (Typeid ( * P) = Typeid (derived ))
{
DP = Static_cast < Derived *> (P );
DP -> Funcb ();
}
Else
P -> Funca ();

}
Int Main ()
{
Base   * CP =   New Derived;
Funcd (CP );
Funcc (CP );
Base   * DP =   New   Base ;
Funcc (DP );
Funcd (DP );
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.