首页 > 代码库 > c++中向上转型(安全)和向下转型(不安全)

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{
    public:
        void myfunc(){
            cout << "B myfunc" << endl;
        }
        virtual void mytest(){
            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;

}

本文出自 “12208412” 博客,请务必保留此出处http://12218412.blog.51cto.com/12208412/1867510

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