使用环境是ubuntu14.04
static_cast和dynamic_cast:
dynamic_cast的机制貌似是转换出错就返回NULL,测试过4种情况:
1) A* a = new B;
B* b=dynamic_cast<B*>(a);
其中,a是b的父类,结果not null;
2) A* a = new B;
C* c=dynamic_cast<C*>(a);
C是B的兄弟类,也继承A,结果null;3) B* b = new D;
C* c = dynamic_cast<C*>(b);
其中,D是B的子类,B和C是兄弟类,结果null;
4) A* a = new A;
E* e = dynamic_cast<E*>(a);
其中,E是不相关的类,结果null。
以上结果显示出,除了第一种情况,dynamic_cast在其他转换上虽然不会报错,但转换是无效的,这是因为dynamic_cast是在运行的时候执行,没法以编译错误的形式显示转换错误,所以只能显示空指针。
将以上情况全用static_cast转换,会发现,1)和2)是not null,3)和4)会报错。
综上,对于下行转换,dynamic_cast只能用于”指向派生类的父类指针转换成对应的派生类指针“,而static_cast可用于父类向任意子类的下行转换。
上述结论仅基于本次实验结果,如果不妥之处,欢迎大家指出!
#include<iostream>
#include<cstring>
using namespace std;
class A
{
public:
int na;
virtual void f()
{
cout<<"hello"<<endl;
};
};
class B:public A
{
public:
int nb;
void f()
{
cout<<"hello2"<<endl;
};
};
class C:public A
{
public:
int nc;
void f()
{
cout << "hello3" << endl;
};
};
class D:public B
{
public:
int nd;
void f()
{
cout << "hello4" << endl;
};
};
class E
{
public:
int ne;
virtual void f()
{
cout<<"hello5"<<endl;
};
};
int main()
{
A* a = new B;
A* a2 = new A;
B* b;
B* b2 = new D; //D是B的子类
C* c;
C* c2; //C是B的兄弟类
C* c3 = new C;
D* d2;
E* e;
//dynamic_cast
b=dynamic_cast<B*>(a2);//结果为not null,对应1)
if(b==NULL)
{
cout<<"null"<<endl;
}
else
{
cout<<"not null"<<endl;
}
c=dynamic_cast<C*>(a);//结果为null,对于2)
if(c==NULL)
{
cout<<"null"<<endl;
}
else
{
cout<<"not null"<<endl;
}
c2=dynamic_cast<C*>(b2);//结果为null,对应3)
if(c2==NULL)
{
cout<<"null"<<endl;
}
else
{
cout<<"not null"<<endl;
}
e=dynamic_cast<E*>(a2);//结果为null,对应4)
if(e==NULL)
{
cout<<"null"<<endl;
}
else
{
cout<<"not null"<<endl;
}
//static_cast
b=static_cast<B*>(a);//结果为not null,对应1) ,将a改成a2,结果一样
if(b==NULL)
{
cout<<"null"<<endl;
}
else
{
cout<<"not null"<<endl;
}
c=static_cast<C*>(a2);//结果为not null,对于2)
if(c==NULL)
{
cout<<"null"<<endl;
}
else
{
cout<<"not null"<<endl;
}
/*c2=static_cast<C*>(b2);//报错,对应3)
if(c2==NULL)
{
cout<<"null"<<endl;
}
else
{
cout<<"not null"<<endl;
}
e=static_cast<E*>(a2);//报错,对应4)
if(e==NULL)
{
cout<<"null"<<endl;
}
else
{
cout<<"not null"<<endl;
}*/
delete(c3);
delete(b2);
delete(a2);
delete(a);
return 0;
}
结果:
null
null
null
null
not null
not null