天天看点

c++中向上转型(安全)和向下转型(不安全)

//基本的向上构造

#include <iostream>                                                                                                                                                              

using namespace std;

class A{

    public:

        void myfunc(){

            cout << "A myfunc" << endl;

        }

        virtual void mytest(){

            cout << "A mytest" << endl;

};

class B:public A{

            cout << "B myfunc" << endl;

            cout << "B mytest"  << endl;

int main(void){

    A* pa = new A();

    B* pb = new B();

    pa = pb;//向上转型,隐式的,是安全的(pb = static_cast<B*>(pa)是向下转型,不安全的.)

    pb->myfunc();//B myfunc

    pb->mytest();//B mytest

    pa->myfunc();//A myfunc

    pa->mytest();//B mytest   向上转型达到,多态的目的.

    return 0;

}

继续阅读