NoVirtualBase* NvirBase = new NovirtualDerivd();

    NvirBase->print();

   // auto nd1 = dynamic_cast<NovirtualDerivd*>(NvirBase);//必须有虚方法

    auto nd11 = static_cast<NovirtualDerivd*>(NvirBase);
    nd11->print2();
    nd11->print();
    delete NvirBase;
dynamic_cast 需要有虚方法的类,否则无法通过编译
这没有虚方法时,父子类转换用static_cast。
static_cast向上得行,向下没有发生类型转换也得行。
std::cout << "============================rtti static_cast====================\n";
   RttiTestBase* b0 = new RttiTestBase();
     auto* b7 = static_cast<RttiTestDerivd2*>(b0);
    if (b7 == nullptr) {
        std::cout << "b7 can not\n";
    }
    else {
        std::cout << "b7 can\n";
        b7->say2();
        b7->say3();
    }
    delete rd1, rd2, b0;
以上代码 从基类对象 b0 向下转换成子类RttiTestDerivd2,发现可以调用只有RttiTestDerivd2这个类里面拥有得方法say3。感觉很神奇。书上说无需进行类型转换就可以,不是很明白。估计那些超类里得成员变量都时默认值吧。
而且最根本得父类得有默认构造函数,我试了,如果根父类没有默认构造函数,向下转换时不行得。
比如RttiTestDerivd2作为间接子类和他得直接父类RttiTestDerivd(代码没给出来)都没有默认构造函数,而RttiTestBase(根父类)却是有一个隐藏得默认构造函数,这种情况下,这种向下转换在我这种情况下是可以得。
如果RttiTestDerivd2里有一个其他类对象 比如A,那么这个A也需要有默认构造函数,我试了,如果没有默认构造函数,是在运行阶段回报错,报错原因是没有合适得构造函数。
 
const_cast 能把一个const指针变为普通指针。