C++的四种类型转换

C++四种强制类型转换

1. static_cast : 用于基本类型间转换,不可用于基本指针类型间转换

例:int i = 4;

 char c = static_cast<char>(i);

2. reinterpret_cast : 用于指针类型之间转换,当浮点型指针转换成整型指针会发生数据截断。

例:double a = 2.1;

double *p1 = &a;

int *p2 = reinterpret_cast<int *>(p1);

3. dynamic_cast : 用于类之间的转换,具有类型检查功能,转换成功返回指指针,不成功返回NULL。

例:class Animal

{

public:

virtual void sleep()

{

printf("Animal is sleeping!\n");

}

};

 

class Monkey : public Animal

{

public:

virtual void sleep()

{

printf("Monkey is sleeping!\n");

}

 

void ClimbTree()

{

printf("Monkey is climbing the tree!\n");

}

};

 

class Giraffe : public Animal

{

public:

virtual void sleep()

{

printf("Giraffe is sleeping!\n");

}

 

void EatLeaf()

{

printf("Giraffe is eating leaves!\n");

}

};

 

void fun(Animal *ptr)

{

ptr->sleep();

Monkey *m = dynamic_cast<Monkey *>(ptr);

if(m!= NULL)

{

m->ClimbTree();

}

 

Giraffe *g = dynamic_cast<Giraffe *>(ptr);

if(g != NULL)

{

g->EatLeaf();

}

}

 

int main()

{

Animal a;

Monkey m;

Giraffe g;

 

fun(&a);

fun(&m);

fun(&g);

return 0;

}

4. const_cast : 可以去除变量的const属性

例如  void fun(const char * str)

{

char *p = const_cast<char *>(str);

p[0] = ‘W’;

}

char str[ ] = “hello”;

fun(str);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值