Class base
{
Public:
Void Iam () {cout <"base \ n ";}
Virtual ~ Base (){}
};
Class derived: public Base
{
Public:
Void Iam () {cout <"derived \ n ";}
Virtual ~ Derived (){}
};
Void testclass (base * P)
{
// Try to output the actual class name here
// P may be a base pointer or a derived pointer.
}
The test cases are as follows:
Base B;
Derived D;
Testclass (& B );
Testclass (& D );
The output is:
Base
Derived
-- From 2kgames intern pen questions
In fact, a parent class and a subclass are given, and a pointer pointing to the class is created. Then, the pointer has been forcibly converted into a pointer pointing to the parent class, then you want to use some method to determine whether the object pointed to by the pointer is actually a real parent class object or a subclass object forced to be a parent class!
Use dynamic_cast to force type conversion. The following solutions are available:
Code
Solution # Include <iostream>
Using namespace STD;
Class base
{
Public:
Void Iam () {cout <"base \ n ";}
Virtual ~ Base (){}
};
Class derived: public Base
{
Public:
Void Iam () {cout <"derived \ n ";}
Virtual ~ Derived (){}
};
Void testclass (base * P)
{
// Try to output the actual class name here
// P may be a base pointer or a derived pointer.
If (derived * temp = dynamic_cast <derived *> (p ))
{
Temp-> Iam ();
}
Else
{
P-> Iam ();
}
}
Int main (INT argc, char * argv [])
{
Base B;
Derived D;
Testclass (& B );
Testclass (& D );
Return 0;
}
The output result displayed on vs2008 is:
Base
Derived
^_^!