c++类型转换
来源:互联网 发布:淘宝网天猫丝巾 编辑:程序博客网 时间:2024/06/04 17:57
前言:c++提供了四种类型转换,分别是static_cast,reinterpret_cast,dynamic_cast,const_cast。它们都有各自的运用场景.
语法形式(四种都一样):
Type dist = *_cast<Type>(src);
1. static_cast(静态类型转换)
c/c++中自动类型转换的数据都可以使用static_cast进行转换,这种类型转换使得c++编译器在编译的时候进行类型检查。
代码例子:
#include <iostream>using namespace std;void testInt(){ cout << "double ==> int" <<endl; double b = 24.3436546; cout << "b:"<< b << endl; int a = (int)b; // c语言类型转换 cout << "c: b ==> a:" << a <<endl; int c = static_cast<int>(b); cout << "c++: b ==> c:" << c <<endl;}void testChar(){ cout << "int ==> char" <<endl; int b = 100; cout << "b:"<< b << endl; char a = (char)b; // c语言类型转换 cout << "c: b ==> a:" << a <<endl; char c = static_cast<char>(b); cout << "c++: b ==> c:" << c <<endl;}int main(){ testInt(); testChar();}
2. reinterpret_cast(重新解释类型)
重新解释类型,有点类似强制转换,如下代码所示:
#include <iostream>using namespace std;class Dog{};class Cat{};int main(){ char* p1 = "the world well be wanderful"; int* p2 = (int*)p1; // c语言类型转换 //int* p3 = static_cast<int*>(p1); int* p3 = reinterpret_cast<int*>(p1); cout << "p1:" << p1 <<endl; cout << "p2:" << p2 <<endl; cout << "p3:" << p3 <<endl; Dog* dog = new Dog(); Cat* cat = reinterpret_cast<Cat*>(dog);}
3. dynamic_cast(动态类型转换)
动态类型转换通常用于将父类指针指向的对象(子类)转换成子类对象。在发生动态的情况下可以用于鉴别父类指针指向的对象的具体类别。
如:
#include <iostream>using namespace std;class Animal{public: virtual void run(){ cout << "Animal is runing..." <<endl; }};class Dog : public Animal{public: void run(){ cout << "Dog is runing..." <<endl; } void doHome(){ cout << "Dog doHome..." <<endl; }};class Cat : public Animal{public: void run(){ cout << "Cat is runing..." <<endl; } void doThing(){ cout << "猫抓老鼠..." <<endl; }};void play(Animal* base){ base->run(); Dog* dog = dynamic_cast<Dog* >(base); if(dog !=NULL){ dog->doHome(); } Cat* cat = dynamic_cast<Cat* >(base); if(cat != NULL){ cat->doThing(); }};int main(){ Dog dog; Cat cat; play(&dog); play(&cat);}
4. const_cast(常量转换)
可以将const修饰的指针变量转换成普通的指针变量。使用时需要确保指针变量指向的内存空间的值确实能修改,如果不能修改则会报错。
#include <iostream>using namespace std;void test(const char* p){ char* p1 = const_cast<char *>(p); p1[3] = 'x';}int main(){ char buf[] = "aaaaaaaaaaaaaaaaaaaaaaaa"; test(buf); cout << buf <<endl; char* p = "aaaaaaaaaaaaaaaaaaaaaaaa"; cout << p <<endl; // test(p); // 程序员要确保变量指向的内存空间确实能修改, // 如果不能修改会带来灾难性的后果}
0 0
- <C/C++> 类型转换
- C/C++:类型转换
- C类型转换
- C#.NET 类型转换
- 类型转换(C#)
- C指针类型转换
- 类型转换--c语言
- C语言类型转换
- C语言类型转换
- C/C++类型转换
- C语言类型转换
- C++_类型转换
- objective-c 类型转换
- objective-c类型转换
- 标准C 类型转换
- c类型转换
- C类型转换
- c类型转换char2short
- linux下动态链接库使用与单步调试
- 直播平台,直播TV介绍,对比,下载等相关信息
- 纯JS实现出生日期[年月日]下拉菜单
- Mybatis学习记录(三)--Mybatis配置文件详解
- pandas:填充缺失值
- c++类型转换
- 分糖果(最短路)
- webkit WinCE port 开发环境搭建过程
- linux/ALSA SRC重采样造成的问题及解决
- 使用Activity做弹窗
- Java classpath and directories
- Linux下的I/O复用与epoll详解
- Java开发中的23种设计模式详解(转)
- 获取签名并转化