逆天的C++:显式类型转换

显式类型转换也叫做强制类型转换,强制转换的操作符包括:static_cast、dynamic_cast、const_cast、reinterpret_cast。

(1)static_cast。C++中所有的隐式类型转换都可以通过此运算符完成,尤其对于会损失精度的大算术类型赋值小算术类型的情况,有了static_cast描述符,编译器便会认为这是条正常语句,而不会报告警告信息;另一个典型的应用场景就是对void 类型指针的类型定义。

const char *str=static_cast<const char *>(malloc(sizeof(char)*10));
int a;
double b=12.33456;
a=static_cast<int>(b);
cout<<"a:"<<a<<endl;

(2)const_cast。编码过程中总有如此情景:一个函数形参类型为非const指针,但是你又不得不传入一个const类型的指针,所以为了解决这个问题,const_cast运算符出现,去掉指针的实参的const属性。

int string_copy(char *str)
{
    char c=str[1];
    str[2]='A';//运行时通过!
    cout<<str[2]<<endl;
    return 1;
 }
 int main()
 {
    const char *str=static_cast<const char *>(malloc(sizeof(char)*10));
    const char * pstr=str;
    string_copy(const_cast<char *>(pstr));
} 
(3)reinterpret_cast。为操作数的为模式提供较低层次的重新解释:

int c=0x01020304;
int *ip=&c;
char *cp=reinterpret_cast<char *>(ip);
cout<<int(*cp)<<endl;
(4)dynamic_cast。将基类的指针转换为子类的指针。

class A
{   
public:
    int a;
    virtual int print() {return a;}
};  
class B:public A
{
    int b;
    int print(){return a;}
};  
class C:public A
{
    int c;
    int print(){return a;}
};   
int main()
{
    B b;
    A *pa=&b;
    C *pb=dynamic_cast<B *>(pa);//如果强制转换成C类型指针,运行时会出错!!
    pb->a=12;
    cout<<pb->a<<endl;
    return 0;
 }                                                                                                                                                                                 

小结:强制转换使C++逐渐向C“靠拢”,默认程序员会清楚自己在干什么,但是这绝对不是程序员想要的!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值