溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

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

發(fā)布時間:2020-07-23 13:09:15 來源:網絡 閱讀:921 作者:神ge 欄目:編程語言

//基本的向上構造

#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   向上轉型達到,多態(tài)的目的.

    return 0;

}


//向上轉型+虛函數
#include <iostream>
using namespace std;

class Integer{
public:
    Integer(int r):m_r(r){}
    virtual Integer& operator+=(const Integer& that){//虛函數可以為拷貝構造函數.
        m_r +=that.m_r;
        return *this;
    }
    int m_r;
};

class Complex:public Integer{
public:
    Complex(int r,int i):Integer(r),m_i(i){}
    Complex& operator+=(const Integer& c){//這里向上轉型,這樣
    //形參既可以接受Integer也可以接受Complex類型的參數.
        Integer::operator+=(c);
        m_i += ((const Complex&)c).m_i;//這里是重點,c有可能是const Integer&類型的
                                    //所以強制轉換,是可行的.
    }
    int m_i;
};

int main(void){
    Complex c1(1,2),c2(3,4);
    c1 += c2;
    cout << c1.m_r << '+' << c1.m_i << 'i' << endl;
    Integer& i1 = c1; // 4+6i;
    Integer& i2 = c2;//3+4i;
    i1+=i2;//i1調用子類Complex的拷貝賦值函數.
    cout << c1.m_r << '+' << c1.m_i << 'i' << endl;//7+10i;
    return 0;

}


向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI