dynamic

    技术2025-07-22  19

    1.upcast

    template <class Container> class Policy1 { public: virtual ~Policy1() {} void Hello1() { cout << "Policy1 hello" << endl; } void Magic1() { Container* pDerived = dynamic_cast<Container*>(this); pDerived->Hello(); } }; template <class Container> class Policy2 { public: virtual ~Policy2() {} void Hello2() { cout << "Policy2 hello" <<endl; } }; class Host: public Policy1<Host>, public Policy2<Host> { public: void Hello() { cout << "Host hello" << endl; } void Magic() { Magic1(); } }; 

    基类要有虚函数,否则会编译出错;static_cast则没有这个限制。基类中需要检测有虚函数的原因:类中存在虚函数,就说明它有想要让基类指针或引用指向派生类对象的情况,此时转换才有意义。

     

      这是由于运行时类型检查需要运行时类型信息,而这个信息存储在类的虚函数表(关于虚函数表的概念,详细可见<Inside c++ object model>)中,只有定义了虚函数的类才有虚函数表,

     

      没有定义虚函数的类是没有虚函数表的。

     

    2.downcast

    class B {...}; class D : public B {...}; void f() { B *pB = new D; B *pB2 = new B; D *pD = dynamic_cast<D*> (pB); // ok. D *pD2 = dynamic_cast<D*> (pB2) // error. }  

    最新回复(0)