cast not needing to perform a run

This question already has an answer here:

  • When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used? 6 answers

  • class Base {
    public:
        virtual ~Base() {}
        // ...
    };
    
    class Derived : public Base {
        // ...
    };
    

    "Typical use":

    void foo(Derived*);
    
    void f(Base* pb)
    {
        if (Derived* pd = dynamic_cast<Derived*>(pb)) {
            foo(pd);
        }
    }
    

    "Above quote":

    void bar(Base*);
    
    void f(Derived* pd)
    {
        Base* pb = dynamic_cast<Base*>(pd); // the dynamic_cast is useless here
                                            //  because a Derived IS-A Base, always
        bar(pb); // Note: could as well call directly bar(pd); (implicit conversion)
    }
    

    dynamic_cast is mostly used for downcast and cross-cast. The gotcha mentions upcast.

    Having structs B1, B2, D:B1, B2:

  • upcast: D* -> B1*, D* -> B2*
  • downcast: D* <- B1*, D* <- B2*
  • cross-cast: B1* <-> B2* (will work if your most derived class is D).
  • 链接地址: http://www.djcxy.com/p/28700.html

    上一篇: 重新解释的目的是什么?

    下一篇: 不需要执行运行