C++中類型轉換

來源:互聯網
上載者: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; // 輸出"class Base1",因為Derive1和Base1之間沒有多態性
//  編譯時間需要加參數 /GR
    class Base2
    {
        virtual void fun( void ) {

                }
    };

    class Derive2 : public Base2
    {

    };
    Derive2 d2;

    Base2& b2 = d2;
    Base2 * p = &d2;
    cout << "3333:"<< typeid(b2).name() << endl; // 輸出"class Derive2",因為Derive1和Base1之間有了多態性

    class Derive22 : public Base2
    {
    };
    // 指標強制轉化失敗後可以比較指標是否為零,而引用卻沒辦法,所以引用制轉化失敗後拋出異常
    Derive2* pb1 = dynamic_cast<Derive2*>(p);
    cout << "333_1:"<< boolalpha << (0!=pb1) << endl; // 輸出"true",因為b2本身就確實是Derive2
    Derive22* pb2 = dynamic_cast<Derive22*>(p);
    cout << "333_2:"<< boolalpha << (0!=pb2) << endl; // 輸出"false",因為b2本身不是Derive22

    try {
        Derive2& rb1 = dynamic_cast<Derive2&>(b2);
        cout << "4444:"<< "true" << endl;
    }
    catch( bad_cast )
    {
        cout << "5555:"<< "false" << endl;
    }
    try {
        Derive22& rb2 = dynamic_cast<Derive22&>(b2);
        cout << "6666:"<< "true" << endl;
    } catch( ... )
    {
        cout << "7777:"<< "false" << endl;
    }
    getchar();
    return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.