走进C++程序世界----类型转换运算符
来源:互联网 发布:福州软件行业协会 编辑:程序博客网 时间:2024/05/17 04:48
C++的四个类型转换运算符已经有很久了,但一直没有弄清楚它们的用法,今天看到一本书上的解释,才大致地的了解了其具体的用法.
看下面具体的代码:
/* *cast_operator.cpp *cDate : 2013-11-16 *Author: sjin *Mail:413977243@qq.com */#include <iostream>using namespace std;/*C++中的类型转换运算符 * 基本格式: * type result = cast_type<type> (source); * *//*static_cast:用于相关类型的指针之间的转换,还可显式地执行标准数据 *类型的类型转换(这种转换将自动或隐式的进行)。用于指针时,static_cast *实现了基本编译阶段的检查,确保指针被转换为相关类型。 *dynamic_cast:在运行阶段执行类型转换,可以检查dynamic_cast操作的结果 *以判断类型的转换是否成功。 *reinterpret_cast:是一种强制类型转换 *const_cast: 是让程序员关闭对象的访问修饰符const。 * */class Animal{public: //虚函数实现为空,不能被调用的。 virtual void Speak() = 0;};class cDog: public Animal{public: void WagTail(){ cout << " Dog: i wagged my tail!" <<endl; } void Speak(){ cout << " Dog: Bow...Bow..." << endl; }};class cCat: public Animal{public: void CatchMice(){ cout << "Cat: i caught a mouse!" << endl; } void Speak(){ cout <<"Cat: Meow!" << endl; }};/*运行阶段判断对象的数据类型,并且调用各自的函数 * */void determinType(const Animal *pAnimal3){ //const_cast 使用 Animal *pAnimal = const_cast<Animal*>(pAnimal3); cDog *pDog = dynamic_cast<cDog*>(pAnimal); if(pDog){ cout << "the Animal is a Dog!" << endl; pDog->WagTail(); } cCat * pcat = dynamic_cast<cCat *>(pAnimal); if(pcat){ cout << " the Animal is a Cat!" << endl; pcat->CatchMice(); }}int main(){ Animal *pAnimal1 = new cDog(); Animal *pAnimal2 = new cCat(); double a = 78.12; double * pd = &a; //reinterpret_cast 强制类型转换使用 //相当于 int *ch = (int *)pd int *ch = reinterpret_cast<int *>(pd); cout << "*ch = " << *ch <<endl; cDog *pDog = static_cast<cDog *>(pAnimal1); //cDog *pDog = static_cast<cDog *>(pAnimal2); //上面这句话会报错的,类型不匹配的 //dynamic_cast 使用 determinType(pAnimal1); determinType(pAnimal2); return 0;}
有更详细的请参阅 http://developer.51cto.com/art/201107/277241.htm
- 走进C++程序世界----类型转换运算符
- 走进C++程序世界------操作符运算、操作符重载、转换运算符、双目元算、+=,-+运算符,比较运算符及下标运算符
- C++:类型转换运算符
- 走进程序世界
- 【C++】强制类型转换运算符
- C类型转换,运算符,math.h
- 如何走进程序的世界?
- 类型转换运算符
- 类型转换运算符
- 类型转换运算符
- 类型转换运算符
- 【c/c++】类型转换函数(类型转换运算符重载函数)
- 走进C++程序世界-------强制数据类型转换(static_cast、dynamic_cast、reinterpret_cast、const_cast)
- C隐式类型转换与运算符优先级
- 【C++】强制类型转换运算符的重载
- C++:关于C++的四个类型转换运算符
- C之运算符与强制类型转换
- 【C++】流插入、提取运算符和类型转换
- Xshell报错“The remote SSH server rejected X11 forwarding request.”
- 如何查看我的订单-REST的流程API设计案例
- BFS——NYOJ 21 三个水杯
- linux 路由表功能解析
- Java:使用wait()与notify()实现线程间协作
- 走进C++程序世界----类型转换运算符
- WAS基本使用手册
- STC-ISP在Windows 7下使用方法
- 指针练习-简易计算器程序
- jquery 简单的跨域取数据
- 解决android使用google map时显示方格的问题
- 原创文章怎么样写才好呢
- html标记<a/>属性href, onclick执行顺序与失效问题解决
- 自学HTML之HTML标签