dynamic_cast主要用于在父类、基类指针的转换。
从派生类指针转向基类指针时,即进行上行转换,是安全的。
从基类指针转向派生类指针时,即进行下行转换,要求基类至少有一个虚函数,并会做安全检查,转换后的指针为空。但是如果基类的指针本来就指向的派生类对象,下行转换也是安全的。
1.dynamic_cast转换基类、派生类指针
class CBase { virtual void dis() {} };
class CDerived : public CBase {};
int main()
{
CBase b; CBase* pb;
CDerived d; CDerived* pd;
pb = dynamic_cast<CBase*>(&d); // ok: derived-to-base
pd = dynamic_cast<CDerived*>(&b); // wrong: base-to-derived
cout << "***********指向基类对象的基类指针转换为派生类指针***********" << endl;
cout << pd << endl;
cout << "***********指向派生类对象的基类指针转换为派生类指针***********" << endl;
pb = new CDerived;
pd = dynamic_cast<CDerived*>(pb);
cout << pb << endl;
cout << pd << endl;
getchar();
return 0;
}
输出结果如下:
2.dynamic_cast转换完全不相关的指针
class CBase { virtual void fun() {} };
class CDerived { virtual void fun() {} };
int main()
{
CBase b; CBase* pb;
CDerived d; CDerived* pd;
pb = dynamic_cast<CBase*>(&d); // ok: derived-to-base
pd = dynamic_cast<CDerived*>(&b); // wrong: base-to-derived
cout << "***********指向基类对象的基类指针转换为派生类指针***********" << endl;
cout << pd << endl;
cout << &b << endl;
cout << "***********指向派生类对象的基类指针转换为派生类指针***********" << endl;
pd = dynamic_cast<CDerived*>(pb);
cout << pb << endl;
cout << pd << endl;
getchar();
return 0;
}
输出结果如下,可见可以转化成成功,但是转换后的指针都被置为NULL。
3. static_cast转换基类、派生类指针
class CBase { virtual void dis() {} };
class CDerived : public CBase {};
int main()
{
CBase b; CBase* pb;
CDerived d; CDerived* pd;
pb = static_cast<CBase*>(&d); // ok: derived-to-base
pd = static_cast<CDerived*>(&b); // wrong: base-to-derived
cout << "***********指向基类对象的基类指针转换为派生类指针***********" << endl;
cout << pd << endl;
cout << &b << endl;
cout << "***********指向派生类对象的基类指针转换为派生类指针***********" << endl;
pb = new CDerived;
pd = static_cast<CDerived*>(pb);
cout << pb << endl;
cout << pd << endl;
getchar();
return 0;
}
结果如下:
可见,当指向基类对象的基类指针转换为派生类指针时,可以转换过来,为之后的使用造成隐患。
4.static_cast转换两个完全不相关的指针
class CBase { };
class CDerived { };
int main()
{
CBase b; CBase* pb;
CDerived d; CDerived* pd;
pb = static_cast<CBase*>(&d); // ok: derived-to-base
pd = static_cast<CDerived*>(&b); // wrong: base-to-derived
cout << "***********指向基类对象的基类指针转换为派生类指针***********" << endl;
cout << pd << endl;
cout << &b << endl;
cout << "***********指向派生类对象的基类指针转换为派生类指针***********" << endl;
pd = static_cast<CDerived*>(pb);
cout << pb << endl;
cout << pd << endl;
getchar();
return 0;
}
编译不通过,提示类型转换无效。