boost 类型转换操作符

来源:互联网 发布:公司域名邮箱注册 编辑:程序博客网 时间:2024/06/05 02:05
struct father { virtual ~father() { }; }; struct mother { virtual ~mother() { }; }; struct child : public father, public mother { }; void func(father *f) { //将f父类的指针 转换为子类的指针,这种叫向下转换child *c = dynamic_cast<child*>(f); } void CMFC08Dlg::OnBnClickedButton2(){//Boost.Exception child *c = new child; func(c); father *f = new child;//定义一个子类,将指针传给父类 mother *m = dynamic_cast<mother*>(f); //将父类的指针转给母类,交叉转换}


struct father { virtual ~father() { }; }; struct mother { virtual ~mother() { }; }; struct child : public father, public mother { }; void func(father *f) { //将f父类的指针 转换为子类的指针,这种叫向下转换//boost::polymorphic_downcast,只能是向下转换操作,它内部使用 static_cast 实现类型转换,它内部使用 static_cast 实现类型转换//实际上在 assert ()函数中使用 dynamic_cast 验证类型转换是否合法,只能在定义了NDEBUG宏的情况下执行child *c = boost::polymorphic_downcast<child*>(f); } void CMFC08Dlg::OnBnClickedButton2(){//Boost.Exception child *c = new child; func(c); father *f = new child;//定义一个子类,将指针传给父类 // boost::polymorphic_cast 其实内部也是使用dynamic_cast,只是他不需要通过返回值检测,他可以抛出异常mother *m = boost::polymorphic_cast<mother*>(f); //将父类的指针转给母类,交叉转换}

#include <boost/lexical_cast.hpp> 

//lexical_cast//1.boost::lexical_cast 内部使用流(streams)执行转换操作。 因此,只有那些重载了 operator<<() 和 operator>>() 这两个操作符的类型可以转换。//2.使用 boost::lexical_cast 的优点是类型转换出现在一行代码之内,无需手工操作流(streams)。 //3.由于流的用法对于类型转换不能立刻理解代码含义, 而 boost::lexical_cast 类型转换操作符还可以使代码更有意义,更加容易理解//4.转换NG情况下,抛出异常boost::bad_lexical_casttry{std::string szData=boost::lexical_cast<string>(3.14156789);TRACE("%s\n",szData.c_str());}catch (boost::bad_lexical_cast& e){TRACE("%s\n",e.what());}
#include <boost/numeric/conversion/cast.hpp> 

//boost::numeric_casttry { int i = 0x10000; //boost::numeric_cast//1.会对需要转换的数字是否能够完全转换,不改变数值的情况下是否能够转换//2.如果不能转换则抛出异常short s = boost::numeric_cast<short>(i); TRACE("%d\n",s) ;} catch (boost::numeric::bad_numeric_cast &e) { //boost::numeric::positive_overflow,boost::numeric::negative_overflow两种异常TRACE("%s\n",e.what());//bad numeric conversion: positive overflow} 


原创粉丝点击