C++类型转换

C++强制转换

1非强制转换 charintdoublefloat

Static_cast<int>( )

 char a = 1;

 int b = static_cast<int>(a);=1

2使用void *的强制类型转换

struct callback_param

{

    void *vp;

};

 int a = 1;

struct callback_param cp;

cp.vp = &a;      //编译器允许从任意类型指针向void*转换

 pr=p;              //error:不能将空类型指针赋给其他指针

 int *ip = static_cast<int *>(cp.vp);

类型转换的意义是调用正确的重载函数

 char buffer[5];

 cout<<(void*)buffer;

输出buffer字符串的地址

errorstray'\243'in program{},()的错误

int i;

float f = 166.7f;

i = static_cast<int>(f);

此时结果,i的值为166

3常量转换(const_cast

const转换为非const,从volatile转换为非volatile。取得const对象的地址,会生成一个指向const的指针,volatile同。

 一、常量指针被转化成非常量指针,并且仍然指向原来的对象;

 二、常量引用被转换成非常量引用,并且仍然指向原来的对象;

 三、常量对象被转换成非常量对象。

const int i = 0;

int *ip = const_cast<int *>(&i);

 

volatile int a = 0;

int *ap = const_cast<int *>(&a);

3、重解释转换(reinterpret_cast

最不安全的一种转换机制,将对象转变为完全不同类型的对象,这是低级的位操作。

 

struct msg_hdr

{

    int msg_type;

    int msg_len;

    char msg_data[0];

};

 

struct msg_data

{

    int data1;

    int data2;

};

 

struct msg_hdr *p = reinterpret_cast<struct msg_hdr *>(recvbuf);

struct msg_data *pdata = reinterpret_cast<struct msg_data *>(p->msg_data);

4

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值