C ++,如何将基础对象向下转换为派生对象?

时间:2017-05-08 06:10:10

标签: c++

关于 downcast 从基类到派生类的问题,请参见示例:

用(2)(3)(4),有助于解释指针引用之间的区别吗?

用(3),如何解释g ++给出的错误信息;

class Base {};
class Derived : public Base {};

int main ()
{
    // example (1)
    Derived d;
    Base* b = &d; // its ok, implict

    // example (2)
    Derived d;
    Base* b = &d;
    Derived* d2 = (Derived*)b; // its ok!

    // example (3)
    Derived d;
    Base& b_ref = d; // its ok, implict
    Derived& d_ref1 = (Derived)b_ref; // error, error: no matching function for call to `Drievd::Drievd(Base&)'

    // example (4)
    Derived& d_ref2 = *((Derived*)(&b_ref)); // its ok
}

0 个答案:

没有答案