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;
}
//向上转型+虚函数#include<iostream>usingnamespacestd;classInteger{public:Integer(intr):m_r(r){}virtualInteger&operator+=(constInteger&that){//虚函数可以为拷贝构造函数.m_r+=that.m_r;return*this;}intm_r;};classComplex:publicInteger{public:Complex(intr,inti):Integer(r),m_i(i){}Complex&operator+=(constInteger&c){//这里向上转型,这样//形参既可以接受Integer也可以接受Complex类型的参数.Integer::operator+=(c);m_i+=((constComplex&)c).m_i;//这里是重点,c有可能是constInteger&类型的//所以强制转换,是可行的.}intm_i;};intmain(void){Complexc1(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;return0;}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。