zoukankan      html  css  js  c++  java
  • dynamic_cast

    #include <typeinfo>
    using std::bad_cast;
    
    #include <iostream>
    using std::cout; using std::endl;
    
    struct A { virtual ~A() { } };
    struct B : virtual public A { /* . . . */ };
    struct C : public B { /* . . . */ };
    struct D : public B, virtual public A { /* . . . */ };
    
    void exercises() {
        A *pa = new C;
        if (B *pb = dynamic_cast< B* >(pa))
             cout << "cast from C to B* ok" << endl;
        else
             cout << "cast from C to B* not ok" << endl;
        B *pb = new B;
        if (C *pc = dynamic_cast< C* >(pb))
             cout << "cast from B to C* ok" << endl;
        else
             cout << "cast from B to C* not ok" << endl;
    
        A *pc = new C;
        if (B *pb = dynamic_cast< B* >(pc))
             cout << "cast C to B* ok" << endl;
        else
             cout << "cast C to B* not ok" << endl;
    
        A *pd = new D;
        if (B *pb = dynamic_cast< B* >(pd))
             cout << "cast D to B* ok" << endl;
        else
             cout << "cast D to B* not ok" << endl;
    }
    
    struct Base {
       virtual ~Base() {};
    };
    
    struct Derived: public Base { };
    
    void cast_to_ref(const Base &b)
    {
        try {
            const Derived &d = dynamic_cast<const Derived&>(b);
        cout<<"success"<<endl;
        // use the Derived object to which b referred
        } catch (bad_cast) {
            cout << "called f with an object that is not a Derived" << endl;
        }
    }
    
    int main()
    {
        Base *bp; 
        bp = new Derived;  // bp actually points to a Derived object
        if (Derived *dp = dynamic_cast<Derived*>(bp)) 
        {
            // use the Derived object to which dp points
        } else {  // bp points at a Base object
            // use the Base object to which bp points
        }
    
        exercises();
        
        cast_to_ref(*bp);
        cast_to_ref(Base());
    }

    j结果如下:

    cast from C to B* ok
    cast from B to C* not ok
    cast C to B* ok
    cast D to B* ok
    success
    called f with an object that is not a Derived
    
  • 相关阅读:
    HTTP 错误 404.2
    SQL Server 2008 R2如何开启数据库的远程连接(转)
    CSS中font-family:中文字体对应的英文名称
    15/18位身份证号码正则表达式(详细版)
    C#获取系统时间及时间格式
    C#正则表达式判断输入日期格式是否正确
    Linux查看机器负载
    模拟HTTP请求超时时间设置
    MySQL show命令的用法
    innodb事务隔离级别
  • 原文地址:https://www.cnblogs.com/wuchanming/p/3758870.html
Copyright © 2011-2022 走看看