温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-07-23 13:09:15 来源:网络 阅读:908 作者:神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   向上转型达到,多态的目的.

    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问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI