C++类型转换运算符的使用

 

C++提供了四个新的类型转换运算符:
const_cast               dynamic_cast
reinterpret_cast      static_cast
 
使用方法: cast_operator   <type>   (object)
                   类型转换操作符   要转换的类型  要进行转换的对象
     dynamic_cast 将一个基类引用或指针转换位一个派生类应用或指针,或者将一个派生类引用或指针转换为一个基类引用或指针。
例:class Shape { ... };
class Circle : public Shape { ... };
Shape *sp;
Circle *cp = dynamic_cast <Circle*> (sp);
 
class Control { ... };
class TextBox : public Control { ... };
Control &cr;
TextBox &ctl = dynamic_cast <Control&> (cr);
 
     static_cast 不局限于同一多态类层次中的基类和派生类,可使用static_cast调用处于不同层次的类型之间的隐式转换。
例:class B { ... };
class D : public B { ... };
void f(B* pb, D* pd)
{
           D* pd2 = static_cast<D*>(pb);        // not safe, pb may
                                         // point to just B
           B* pb2 = static_cast<B*>(pd);        // safe conversion
           ...
}
     reinterpret_cast 将指针类型转换为其他指针类型,将数字转换为指针或将指针转换为数字。
例: void * getmen()
{
   static char buf[100];
   …
   return buf;
}
char *cp = reinterpret_cast<char *> (getmen);
     const_cast 移去对象的const, volatile, 和 __unaligned属性。
例:class CCTest
{
public:
            void setNumber( int );
            void printNumber() const;
private:
            int number;
};
void CCTest::setNumber( int num )
{
number = num;
}
void CCTest::printNumber() const
{
            cout << "/nBefore: " << number;
            const_cast< CCTest * >( this )->number--;
            cout << "/nAfter: " << number;
}

 

 

推荐网站:好巴鹿(http://www.haobalu.com 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值