成人午夜视频全免费观看高清-秋霞福利视频一区二区三区-国产精品久久久久电影小说-亚洲不卡区三一区三区一区

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

//基本的向上構(gòu)造

為康樂(lè)等地區(qū)用戶提供了全套網(wǎng)頁(yè)設(shè)計(jì)制作服務(wù),及康樂(lè)網(wǎng)站建設(shè)行業(yè)解決方案。主營(yíng)業(yè)務(wù)為網(wǎng)站設(shè)計(jì)制作、網(wǎng)站設(shè)計(jì)、康樂(lè)網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠(chéng)的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長(zhǎng)期合作。這樣,我們也可以走得更遠(yuǎn)!

#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;//向上轉(zhuǎn)型,隱式的,是安全的(pb = static_cast<B*>(pa)是向下轉(zhuǎn)型,不安全的.)
    

    pb->myfunc();//B myfunc
    pb->mytest();//B mytest

    pa->myfunc();//A myfunc

    pa->mytest();//B mytest   向上轉(zhuǎn)型達(dá)到,多態(tài)的目的.

    return 0;

}

//向上轉(zhuǎn)型+虛函數(shù)
#include <iostream>
using namespace std;

class Integer{
public:
    Integer(int r):m_r(r){}
    virtual Integer& operator+=(const Integer& that){//虛函數(shù)可以為拷貝構(gòu)造函數(shù).
        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){//這里向上轉(zhuǎn)型,這樣
    //形參既可以接受Integer也可以接受Complex類型的參數(shù).
        Integer::operator+=(c);
        m_i += ((const Complex&)c).m_i;//這里是重點(diǎn),c有可能是const Integer&類型的
                                    //所以強(qiáng)制轉(zhuǎn)換,是可行的.
    }
    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調(diào)用子類Complex的拷貝賦值函數(shù).
    cout << c1.m_r << '+' << c1.m_i << 'i' << endl;//7+10i;
    return 0;

}

當(dāng)前名稱:c++中向上轉(zhuǎn)型(安全)和向下轉(zhuǎn)型(不安全)
本文鏈接:http://jinyejixie.com/article40/ppsceo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站制作、、網(wǎng)站收錄網(wǎng)站導(dǎo)航、網(wǎng)站排名云服務(wù)器

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

網(wǎng)站托管運(yùn)營(yíng)