类static_cast、dynamic_cast与RTTI

1、static_cast

class Base {
    public:
        virtual void f() {
            cout << "Base::f() " << endl;
        }

};

class Derive: public Base {
    public:
        virtual void f() {
            cout << "Derive::f() " << endl;
        }

        virtual void f2() {
            cout << "Derive::f2() " << endl;
        }
};

int main(){
    // static_cast
    Base *pb1 = new Derive();
    Derive *pd1 = static_cast<Derive*>(pb1);
    pd1 -> f();

    Base *pb2 = new Base();
    Derive *pd2 = static_cast<Derive*>(pb2);
    pd2 -> f();
    //pd2 -> f2();  // core, base no f2()

    delete pb1;
    delete pb2;
    return 0;
}

static_cast可以在基类和派生类之间转换(偏移指针),编译时确定,不保证类型转换安全。

2、dynamic_cast

class Base {
    public:
        virtual void f() {
            cout << "Base::f() " << endl;
        }

};

class Derive: public Base {
    public:
        virtual void f() {
            cout << "Derive::f() " << endl;
        }

        virtual void f2() {
            cout << "Derive::f2() " << endl;
        }
};

int main(){
// dynamic_cast
    Base *pb3 = new Derive();
    Derive *pd3 = dynamic_cast<Derive*>(pb3);   // down cast
    pd3 -> f();

    Base *pb4 = new Base();
    Derive *pd4 = dynamic_cast<Derive*>(pb4);   // up cast 
    if(pd4){                    // pd4 is NULL here
        pd4 -> f();
        pd4 -> f2(); 
    }

    delete pb3;
    delete pb4;

    return 0;
}

专门用于用于有继承关系类之间转换,尤其是向下转换,运行时确定,是类型安全的。

3、RTTI

Leave a Reply

Your email address will not be published. Required fields are marked *