关于dynamic_cast、static_cast转换做安全检查的不同

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;
}

 编译不通过,提示类型转换无效。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值