boost::static_pointer_cast、boost::dynamic_pointer_cast和boost::const_pointer_cast

当我们用“裸”指针进行类层次上的上下行转换时,可以使用dynamic_cast。当然我们也可以使用static_cast,只是dynamic_cast在进行下行转换的时候(即基类到派生类)具有类型检查功能,而static_cast没有。因此存在安全问题。

当我们使用智能指针时,如果需要进行类层次上的上下行转换时,可以使用boost::static_pointer_cast和boost::dynamic_pointer_cast。(C++11中也支持智能指针和转换,只是命名空间改成std即可)。

1. static_pointer_cast

#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>

using namespace std;

class CBase
{
public:
	CBase() { }
	virtual ~CBase() { }

	void myBase()
	{
		cout << "CBase::myBase" << endl;
	}
};

class CDerive : public CBase
{
public:
	CDerive() { }
	~CDerive() { }

	void myDerive()
	{
		cout << "CDerive::myDerive" << endl;
	}
};

int main(void)
{
	//上行的转换(派生类到基类的转换)
	boost::shared_ptr<CDerive> spDeriveUp;
	boost::shared_ptr<CBase> spBaseUp;
	spDeriveUp = boost
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值