C++-static_cast揭密

/**********************************************************
static_cast<>揭密
      简而言之,static_cast<> 将尝试转换,举例来说,如float-到-integer,
而reinterpret_cast<>简单改变编译器的意图重新考虑那个对象作为另一类型。
http://www.vckbase.com/document/viewdoc/?id=1651
********************************************************
*/

class  CBaseX
{
public:
    
int x;
    CBaseX() 
    

        x 
= 10
    }

    
void foo() 
    

        printf(
"CBaseX::foo() x=%d ", x); 
    }

}
;
class  CBaseY
{
public:
    
int y;
    
int* py;
    CBaseY() 
    

        y 
= 20
        py 
= &y; 
    }

    
void bar() 
    

        printf(
"CBaseY::bar() y=%d, *py=%d ", y, *py); 
    }

}
;
class  CDerived :  public  CBaseX,  public  CBaseY
{
public:
    
int z;
}
;

void  main()
{
    
int a = 100;
    
float b = 12.324;
    a 
= static_cast<int>(b); //正确.成功将 float 转换成了 int
    cout<<a<<endl;

    
int a = 100;
    
int *= &a;
    
float *= static_cast<float*>(p); //错,这里不能将int*转换成float*

    
int a = 100;
    
void *= &a;
    
float *= static_cast<float*>(p); //正确.可以将void*转换成float*
    CBaseX *pX = new CBaseX();
    CBaseY 
*pY1 = static_cast<CBaseY*>(pX); //错误,不能将CBaseX*转换成CBaseY*

    CBaseX 
*pX = new CBaseX();
    CBaseY 
*pY1 = reinterpret_cast<CBaseY*>(pX); //正确. “欺骗”编译器
    pY1->bar(); //崩溃

//正如我们在泛型例子中所认识到的,如果你尝试转换一个对象到另一个
//无关的类static_cast<>将失败,而reinterpret_cast<>就总是成功“欺骗”
//编译器:那个对象就是那个无关类
}
 
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值