Type conversion in C ++

Source: Internet
Author: User

# Include <iostream>
Using namespace STD;
Int main (void)
{

Cout <"1111:" <typeid (1.1f). Name () <Endl;
Cout <"1111:" <typeid (1). Name () <Endl;
Cout <"1111:" <typeid ('C'). Name () <Endl;
Class base1
{
};

Class derive1: Public base1
{
};
Derive1 D1;
Base1 & b1 = D1;
Cout <"2222:" <typeid (B1). Name () <Endl; // output "class base1" because there is no polymorphism between derive1 and base1
// Add the parameter/GR during compilation
Class base2
{
Virtual void fun (void ){

}
};

Class derive2: Public base2
{

};
Derive2 D2;

Base2 & b2 = d2;
Base2 * P = & D2;
Cout <"3333:" <typeid (B2). Name () <Endl; // output "class derive2" because there is a polymorphism between derive1 and base1

class derive22: Public base2
{< BR >};
// after the forced conversion of the pointer fails, you can compare whether the pointer is zero, but there is no way to reference it, therefore, an exception is thrown after the conversion fails.
derive2 * PB1 = dynamic_cast (p);
cout <"333_1: " derive22 * master = dynamic_cast (P );
cout <"333_2:"

try {
derive2 & rb= dynamic_cast (B2);
cout <"4444:" <"true" }< br> catch (bad_cast)
{< br> cout <"5555:" <"false" }< br> try {
derive22 & Rb2 = dynamic_cast (B2);
cout <"6666: "<" true " } catch (...)
{< br> cout <"7777:" <"false" }< br> getchar ();
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.