Type Casting

Type Casting
headlogo1.gifheadlogo2.gif
headlogo3.gif  C++ : Documents : C++ Language Tutorial : Type Casting
  Search:
userpass[register]
javascript and cookies required
165x1.gif165x1.gif
C++ Language Tutorial
Introduction
?Instructions for use
Basics of C++
?Structure of a program
?Variables. Data Types.
?Constants
?Operators
?Basic Input/Output
Control Structures
?Control Structures
?Functions (I)
?Functions (II)
Compound Data Types
?Arrays
?Character Sequences
?Pointers
?Dynamic Memory
?Data Structures
?Other Data Types
Object Oriented Programming
?Classes (I)
?Classes (II)
?Friendship and inheritance
?Polymorphism
Advanced Concepts
?Templates
?Namespaces
?Exceptions
?Type Casting
?Preprocessor directives
C++ Standard Library
?Input/Output with files
Document categories
Information about C++
C++ Language Tutorial
Additional Papers
User-contributed
cplusplus.com
documents
reference
sourcecodes
forum

165x1.gif1x1.gif get.media?sid=4636&m=3&tp=7&d=s&c=1 165x1.gif
get.media?sid=4636&m=1&tp=5&d=s&c=1

Type Casting

Published by Juan Soulie
Last update on Nov 2, 2005 at 1:42am
Converting an expression of a given type into another type is known as type-casting. We have already seen some ways to type cast:

Implicit conversion

Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. For example:

 a=2000; b;b=a;

Here, the value of a has been promoted from short to int and we have not had to specify any type-casting operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and allow conversions such as the conversions between numerical types (short to int, int to float, double to int...), to or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision, which the compiler can signal with a warning. This can be avoided with an explicit conversion.

Implicit conversions also include constructor or operator conversions, which affect classes that include specific constructors or operator functions to perform conversions. For example:

 A {}; B { : B (A a) {} };A a;B b=a;

Here, a implicit conversion happened between objects of class A and class B, because B has a constructor that takes an object of class A as parameter. Therefore implicit conversions from A to B are allowed.

Explicit conversion

C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. We have already seen two notations for explicit type conversion: functional and c-like casting:

 a=2000; b;b = () a;    b =  (a);    

The functionality of these explicit conversion operators is enough for most needs with fundamental data types. However, these operators can be applied indiscriminately on classes and pointers to classes, which can lead to code that while being syntactically correct can cause runtime errors. For example, the following code is syntactically correct:

  std; CDummy { i,j;}; CAddition { x,y;:CAddition ( a,  b) { x=a; y=b; } result() {  x+y;}}; main () {CDummy d;CAddition * padd;padd = (CAddition*) &d;cout << padd->result(); 0;}
                        

The program declares a pointer to CAddition, but then it assigns to it a reference to an object of another incompatible type using explicit type-casting:

padd = (CAddition*) &d;

Traditional explicit type-casting allows to convert any pointer into any other pointer type, independently of the types they point to. The subsequent call to member result will produce either a run-time error or a unexpected result.

In order to control these types of conversions between classes, we have four specific casting operators: dynamic_cast, reinterpret_cast, static_cast and const_cast. Their format is to follow the new type enclosed between angle-brackets (<>) and immediately after, the expression to be converted between parentheses.

dynamic_cast <new_type> (expression)
reinterpret_cast <new_type> (expression)
static_cast <new_type> (expression)
const_cast <new_type> (expression)

The traditional type-casting equivalents to these expressions would be:

(new_type) expression
new_type (expression)

but each one with its own special characteristics:

dynamic_cast

dynamic_cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.

Therefore, dynamic_cast is always successful when we cast a class to one of its base classes:

 CBase { }; CDerived:  CBase { };CBase b; CBase* pb;CDerived d; CDerived* pd;pb = <CBase*>(&d);     pd = <CDerived*>(&b);  

The second conversion in this piece of code would produce a compilation error since base-to-derived conversions are not allowed with dynamic_cast unless the base class is polymorphic.

When a class is polymorphic, dynamic_cast performs a special checking during runtime to ensure that the expression yields a valid complete object of the requested class:

  std; CBase {  dummy() {} }; CDerived:  CBase {  a; }; main () { {CBase * pba =  CDerived;CBase * pbb =  CBase;CDerived * pd;pd = <CDerived*>(pba); (pd==0) cout <<  << endl;pd = <CDerived*>(pbb); (pd==0) cout <<  << endl;}  (exception& e) {cout <<  << e.what();} 0;}
Null pointer on second type-cast

Compatibility note: dynamic_cast requires the Run-Time Type Information (RTTI) to keep track of dynamic types. Some compilers include this feature as an option which is disabled by default. This feature must be enabled for runtime type checking using dynamic_cast.

The code tries to perform two dynamic casts from pointer objects of type CBase* (pba and pbb) to a pointer object of type CDerived*, but only the second one is successful. Notice their respective initializations:

CBase * pba =  CDerived;CBase * pbb =  CBase;

Even though both are pointers of type CBase*, pba points to an object of type CDerived, while pbb points to an object of type CBase. Thus, when their respective type-castings are performed using dynamic_cast, pba is pointing to a full object of class CDerived, whereas pbb is pointing to an object of class CBase, which is an incomplete object of class CDerived.

When dynamic_cast cannot cast a pointer because it is not a complete object of the required class -as in the second conversion in the previous example- it returns a null pointer to indicate the failure. If dynamic_cast is used to convert to a reference type and the conversion is not possible, an exception of type bad_alloc is thrown instead.

dynamic_cast can also cast null pointers even between pointers to unrelated classes, and can also cast pointers of any type to void pointers (void*).

static_cast

static_cast can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived. This ensures that at least the classes are compatible if the proper object is converted, but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe. On the other side, the overhead of the type-safety checks of dynamic_cast is avoided.

 CBase {}; CDerived:  CBase {};CBase * a =  CBase;CDerived * b = <CDerived*>(a);

This would be valid, although b would point to an incomplete object of the class and could lead to runtime errors if dereferenced.

static_cast can also be used to perform any other non-pointer conversion that could also be performed implicitly, like for example standard conversion between fundamental types:

 d=3.14159265; i = <>(d);

Or any conversion between classes with explicit constructors or operator functions as described in "implicit conversions" above.

reinterpret_cast

reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes. The operation result is a simple binary copy of the value from one pointer to the other. All pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked.

It can also cast pointers to or from integer types. The format in which this integer value represents a pointer is platform-specific. The only guarantee is that a pointer cast to an integer type large enough to fully contain it, is granted to be able to be cast back to a valid pointer.

The conversions that can be performed by reinterpret_cast but not by static_cast have no specific uses in C++ are low-level operations, whose interpretation results in code which is generally system-specific, and thus non-portable. For example:

 A {}; B {};A * a =  A;B * b = <B*>(a);

This is valid C++ code, although it does not make much sense, since now we have a pointer that points to an object of an incompatible class, and thus dereferencing it is unsafe.

const_cast

This type of casting manipulates the constness of an object, either to be set or to be removed. For example, in order to pass a const argument to a function that expects a non-constant parameter:

  std; print ( * str){cout << str << endl;} main () {  * c = ;print ( < *> (c) ); 0;}
sample text

typeid

typeid allows to check the type of an expression:

typeid (expression)

This operator returns a reference to a constant object of type type_info that is defined in the standard header file <typeinfo>. This returned value can be compared with another one using operators == and != or can serve to obtain a null-terminated character sequence representing the data type or class name by using its name() member.

  std; main () { * a,b;a=0; b=0; ((a) != (b)){cout << ;cout <<  << (a).name() << ;cout <<  << (b).name() << ;} 0;}
a and b are of different types:a is: int *b is: int

When typeid is applied to classes typeid uses the RTTI to keep track of the type of dynamic objects. When typeid is applied to an expression whose type is a polymorphic class, the result is the type of the most derived complete object:

  std; CBase { f(){} }; CDerived :  CBase {}; main () { {CBase* a =  CBase;CBase* b =  CDerived;cout <<  << (a).name() << ;cout <<  << (b).name() << ;cout <<  << (*a).name() << ;cout <<  << (*b).name() << ;}  (exception& e) { cout <<  << e.what() << endl; } 0;}
a is: class CBase *b is: class CBase **a is: class CBase*b is: class CDerived

Notice how the type that typeid considers for pointers is the pointer type itself (both a and b are of type class CBase *). However, when typeid is applied to objects (like *a and *b) typeid yields their dynamic type (i.e. the type of their most derived complete object).

If the type typeid evaluates is a pointer preceded by the dereference operator (*), and this pointer has a null value, typeid throws a bad_typeid exception.

navigate_previous.gifPrevious:
Exceptions
navigate_index.gif
index
navigate_next.gifNext:
Preprocessor directives

 

© The C++ Resources Network, 2000-2005 - All rights reserved
posted on 2006-04-13 11:27 horily 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/horily/archive/2006/04/13/374109.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/300437.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

世界最牛实验室,堪称诺贝尔奖孵化器!到底是个怎样神奇的存在?!

▲ 点击查看随着诺贝尔各个奖项陆陆续续的公布&#xff0c;卡文迪许实验室&#xff0c;又开始重回大众视野。在这个世界最牛实验室之一的实验室里&#xff0c;仅仅过去了一百多年&#xff0c;就不断涌现出一批又一批世界一流的科学家&#xff1a;把电与磁进行有机统一的麦克斯…

java接口那一节是哪的知识_Java中的接口知识汇总

Java中的接口知识汇总发布于 2020-4-29|复制链接本文给大家汇总介绍了在java中的接口知识&#xff0c;包括为什么要使用接口、什么是接口、抽象类和接口的区别、如何定义接口以及定义接口注意点&#xff0c;希望大家能够喜欢一.为什么要使用接口 假如有一个需求&#xff1a;要求…

用C语言实现解析简单配置文件的小工具

本文介绍作者写的一个小工具&#xff0c;简单的代码中包含了C语言对字符串的处理技巧&#xff0c;对文本文件的简单解析&#xff0c;二进制文件的数据复制的方法&#xff0c;以及格式化输出文本文件的示例。 工具的输入是如下内容的配置文件&#xff1a; [plain] view plaincop…

Delphi应用程序在命令行下带参数执行返回命令行提示的问题

在命令行模式&#xff08;CMD&#xff09;下执行时&#xff0c;想获得执行参数&#xff0c;用以下变量&#xff1a; ParamCount&#xff1a;参数个数 ParamStr&#xff1a;为参数数组 如果想在执行完一个操作后在命令行作出相应提示&#xff0c;就应该在相应位置放入…

开源的负载测试/压力测试工具 NBomber

负载测试和压力测试对于确保 web 应用的性能和可缩放性非常重要。尽管它们的某些测试是相同的&#xff0c;但目标不同。负载测试&#xff1a;测试应用是否可以在特定情况下处理指定的用户负载&#xff0c;同时仍满足响应目标。应用在正常状态下运行。压力测试&#xff1a;在极端…

人生失败的31种致命原因

人生失败的31种致命原因 一、不利的遗传背景。天生智力不足的人&#xff0c;是没什么办法可想的。唯一的补救办法就是“以勤补拙”。 二、缺乏明确的人生目标&#xff0c;凡是没有明确人生目标的人&#xff0c;便没有成功的希望&#xff0c;在我曾经分析过的100人中&#x…

男人都应该懂的一张图。。 | 今日趣图

全世界只有3.14 % 的人关注了青少年数学之旅美国人为了教民众如何辨别韩国人制作的韩国女性标准照左右军事成为一个有钱人的概率有多高&#xff1f;最新版男人都该懂的汽车品牌从属关系图twi:NOCO_1002肥胖和骨架没有必然联系800斤胖子的X射线照 科普君XueShu 雪树来猜一猜这是…

python 抓取的网页默认是bytes的,要转码

python 抓取的网页默认是bytes的,要转码.查看网页源码可以看到,我本次抓取的网页的编码方式是utf-8的.req urllib.request.Request(urlmyurl,headers myheaders) data urllib.request.urlopen(req).read() print(data.decode("UTF-8"))这样就正常显示中文了转载于…

FireFox与IE的兼容

1. JavaScript对象的引用 为了减少JavaScript对象的下载次数&#xff0c;Tasian只会在浏览器第一次请求应用时才会下载JavaScript文件。JavaScript对象只会驻留在Top级窗体&#xff0c;任何其它窗体需要引用到该JavaScript对象&#xff0c;只需要在引如下的方式进行引用就行&am…

多语言应用开发中本地化信息对照表

多语言应用开发中本地化信息对照表。包含区域编号、本地化名称、英语名称、中文名称、国家地区码、语言代码和流通币种等。区域编号本地化名称英语名称中文名称国家地区语言流通币种排序id-idBahasa IndonesiaIndonesian印度尼西亚语IDidIDR1ms-myBahasa MelayuMalay (Malaysia…

学做菜咯

以前在QQ空间发的贴&#xff0c;现在转到这边来&#xff0c;嘿嘿。青蛙达 - 07月28日- 14时28分今天中午做我个人最喜欢的菜之一《咖喱鸡饭》 早上到超市买了&#xff1a; 大蒜头、洋葱、南瓜、鸡翅膀、咖喱粉、胡椒粉、白糖、桂皮 回来发现原来把辣椒粉当成胡椒粉买回来了....…

java一般方法有哪些方法有哪些方法_Java代码优化有哪些方法?

Java代码优化是Java编程开发很重要的一个步骤&#xff0c;Java代码优化要注重细节优化&#xff0c;一个两个的细节的优化&#xff0c;产生的效果不大&#xff0c;但是如果处处都能注意代码优化&#xff0c;对代码减少体积、提高代码运行效率是有巨大帮助的&#xff0c;还能在一…

Facebook 中国程序员之死

全世界只有3.14 % 的人关注了青少年数学之旅9 月 19 日&#xff0c;一位 Facebook 软件工程师从加州门洛帕克&#xff08;Menlo Park&#xff09;总部四楼纵身跳下&#xff0c;结束年轻的生命。Facebook 新闻发言人证实确有其事&#xff0c;并说公司将会联系员工家人。门洛帕克…

HTTP头信息

通常 HTTP 消息包括客户机向服务器的请求消息和服务器向客户机的响应消息。这两种类型的消息由一个起始行,一个或者多个头域,一个只是头域结束的空行和可选的消息体组成。HTTP 的头域包括通用头,请求头,响应头和实体头四个部分。每个头域由一个域名,冒号(:)和域值三部分组成。域…

[导入]数据库物理模型设计的其他模式之继承模式

连载之7原创&#xff1a;胖子刘&#xff08;转载请注明作者和出处&#xff0c;谢谢&#xff09;数据库物理模型设计的其他模式除了上面提到的四种主要设计模式&#xff0c;还有一些其他模式&#xff0c;在某些项目中可能会用到&#xff0c;在这里先简单做个说明&#xff0c;暂不…

最近ゲームにはまってる。

小D的[今日口语]栏目里今天教的一句话正好表达了我最近的状态最近&#xff08;さいきん&#xff09;ゲームにはまってる&#xff08;最近我很迷游戏&#xff09;这个“迷”字用得很对感觉自己现在还是孩子状态会沉溺于一种东西而无法自拔周末的时候一般都是游戏完累了才有心情去…

dialog element 删掉标题_ElementUI 销毁Dialog数据(简单粗暴)

在使用element开发通过之中使用Dialog弹窗创建数据或者数据回显在经常不过了。而且数据创建和数据编辑正常都是使用同一组件。出现的问题&#xff1a;title"提示弹窗":visible.sync"dialogVisible"width"30%"destroy-on-close>使用dialog 提供…

一个简单的方式搞定密码的加盐哈希与验证

过去一段时间来, 众多的网站遭遇用户密码数据库泄露事件。层出不穷的类似事件对用户会造成巨大的影响&#xff0c;因为人们往往习惯在不同网站使用相同的密码&#xff0c;一家 “暴库”&#xff0c;全部遭殃。单向加密一个简单的方案是将明文密码做单向哈希后存储。单向哈希算法…

“我数学太烂,但高考136分!”刷完上万道题后,我找到2个月多考58分的捷径…...

全世界只有3.14 %的人关注了青少年数学之旅01难上天的高考试卷&#xff0c;我逆袭考到136分&#xff01;我叫刘辉&#xff0c;来自湖北省的某个县城&#xff0c;今年我数学考到了136分的好成绩&#xff0c;成功被一所985高校录取。↓我的高考成绩↓但回想一年之前&#xff0c;我…

php吞了throw错误,PHP 异常与错误处理

异常处理&#xff1a;意外&#xff0c;是在程序运行过程中发生的意料之外的事&#xff0c;使用异常改变脚本正常流程。try{}catch(异常对象){}如果try中代码没问题&#xff0c;则执行完try中代码后就到catch后执行如果try中代码有异常发生&#xff0c;则抛出一个异常对象&#…