您的位置:首页 > 其它

boost学习-3.conversion,多态类型之间的安全转型,与数据类型转换

2010-02-25 13:15 567 查看
这个库比较简单,看例子就明白啦

1.多态类型之间的安全转型

polymorphic_cast 和 polymorphic_downcast

namespace boost {

template <class Derived, class Base>
inline Derived polymorphic_cast(Base* x);
// 抛出: std::bad_cast 如果 ( dynamic_cast<Derived>(x) == 0 )
// 返回: dynamic_cast<Derived>(x)

template <class Derived, class Base>
inline Derived polymorphic_downcast(Base* x);
// 效果: assert( dynamic_cast<Derived>(x) == x );
// 返回: static_cast<Derived>(x)

}
#include <boost/cast.hpp>
...
class Fruit { public: virtual ~Fruit(){}; ... };
class Banana : public Fruit { ... };
...
void f( Fruit * fruit ) {
// ... 我们确信 fruit 是一个 Banana
Banana * banana = boost::polymorphic_downcast<Banana*>(fruit);
...

2.数据类型转换

lexical_cast<>

#include <iostream>
#include <boost/lexical_cast.hpp>
using namespace boost;
using namespace std;
int main()
{
int i = lexical_cast<int>("123444");
cout<<"i="<<i<<endl;
string s = lexical_cast<string>(i);
cout<<"string s = "<<s<<endl;
double d1 = 1.345678900;
s = lexical_cast<string>(d1);
cout<<"string s = "<<s<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: