C++中的类型转换

c++对象模型笔记:指针类型转换 这篇笔记说的是关于c/c++中的类型转换的东西,重点是与指针有关的类型。1、强制类型转换看一下这个c代码:int a = 0x123456;  //0x是十六进制的表示法char c = (char)a;printf("%d/n", c);在我的编译环境里输出的是什么呢? 是86,怎么得来的呢?(我的编译环境见“概述”)int a的内存如下(左边是低地址的内容,右边是高地址的内容):0x56  0 阅读详情

1、static_cast Operator

MSDN:

The expression static_cast < type-id > ( expression ) converts expression to the type of type-id based solely on the types present in the expression. No run-time type check is made to ensure the safety of the conversion.

Syntax

static_cast < type-id > ( expression )

The static_cast operator can be used for operations such as converting a pointer to a base class to a pointer to a derived class. Such conversions are not always safe. For example:

class B { ... };

class D : public B { ... };

void f(B* pb, D* pd)
{
   D* pd2 = static_cast<D*>(pb);        // not safe, pb may
                                                       // point to just B

   B* pb2 = static_cast<B*>(pd);        // safe conversion
   ...
}

In contrast to dynamic_cast, no run-time check is made on the static_cast conversion of pb. The object pointed to by pb may not be an object of type D, in which case the use of *pd2 could be disastrous. For instance, calling a function that is a member of the D class, but not the B class, could result in an access violation.

The dynamic_cast and static_cast operators move a pointer throughout a class hierarchy. However, static_cast relies exclusively on the information provided in the cast statement and can therefore be unsafe. For example:

class B { ... };
class D : public B { ... };

void f(B* pb)
{
  D* pd1 = dynamic_cast<D*>(pb);
  D* pd2 = static_cast<D*>(pb);
}

If pb really points to an object of type D, then pd1 and pd2 will get the same value. They will also get the same value if pb == 0.

If pb points to an object of type B and not to the complete D class, then dynamic_cast will know enough to return zero. However, static_cast relies on the programmer’s assertion that pb points to an object of type D and simply returns a pointer to that supposed D object.

Consequently, static_cast can do the inverse of implicit conversions, in which case the results are undefined. It is left to the programmer to ensure that the results of a static_cast conversion are safe.

This behavior also applies to types other than class types. For instance, static_cast can be used to convert from an int to a char. However, the resulting char may not have enough bits to hold the entire int value. Again, it is left to the programmer to ensure that the results of a static_cast conversion are safe.

The static_cast operator can also be used to perform any implicit conversion, including standard conversions and user-defined conversions. For example:

typedef unsigned char BYTE

void f()
{
  char ch;
  int i = 65;
  float f = 2.5;
  double dbl;

  ch = static_cast<char>(i);              // int to char
  dbl = static_cast<double>(f);         // float to double
  ...
  i = static_cast<BYTE>(ch);
  ...
}

The static_cast operator can explicitly convert an integral value to an enumeration type. If the value of the integral type does not fall within the range of enumeration values, the resulting enumeration value is undefined.

The static_cast operator converts a null pointer value to the null pointer value of the destination type.

Any expression can be explicitly converted to type void by the static_cast operator. The destination void type can optionally include the const, volatile, or __unaligned attribute.

The static_cast operator cannot cast away the const, volatile, or __unaligned attributes.

static_cast在功能上基本上与C风格的类型转换一样强大,含义也一样。它也有功能上限制。例如,你不能用static_cast象用C风格的类型转换一样把struct转换成int类型或者把double类型转换成指针类型,另外,static_cast不能从表达式中去除const属性,因为另一个新的类型转换操作符const_cast有这样的功能。

2、const_cast Operator

MSDN:

The const_cast operator can be used to remove the const, volatile, and __unaligned attribute(s) from a class.

Syntax

const_cast < type-id > ( expression )

A pointer to any object type or a pointer to a data member can be explicitly converted to a type that is identical except for the const, volatile, and __unaligned qualifiers. For pointers and references, the result will refer to the original object. For pointers to data members, the result will refer to the same member as the original (uncast) pointer to data member. Depending on the type of the referenced object, a write operation through the resulting pointer, reference, or pointer to data member might produce undefined behavior.

The const_cast operator converts a null pointer value to the null pointer value of the destination type.

const_cast用于类型转换掉表达式的const或volatileness属性。通过使用const_cast,你向人们和编译器强调你通过类型转换想做的只是改变一些东西的constness或者 volatileness属性。这个含义被编译器所约束。如果你试图使用const_cast来完成修改constness 或者volatileness属性之外的事情,你的类型转换将被拒绝。

3、dynamic_cast Operator

MSDN:

The expression dynamic_cast<type-id>( expression ) converts the operand expression to an object of type type-id. The type-id must be a pointer or a reference to a previously defined class type or a “pointer to void”. The type of expression must be a pointer if type-id is a pointer, or an l-value if type-id is a reference.

Syntax

dynamic_cast < type-id > ( expression )

If type-id is a pointer to an unambiguous accessible direct or indirect base class of expression, a pointer to the unique subobject of type type-id is the result. For example:

class B { ... };
class C : public B { ... };
class D : public C { ... };

void f(D* pd)
{
  C* pc = dynamic_cast<C*>(pd);   // ok: C is a direct base class
                          // pc points to C subobject of pd

  B* pb = dynamic_cast<B*>(pd);   // ok: B is an indirect base class
                          // pb points to B subobject of pd
  ...
}

This type of conversion is called an “upcast” because it moves a pointer up a class hierarchy, from a derived class to a class it is derived from. An upcast is an implicit conversion.

If type-id is void*, a run-time check is made to determine the actual type of expression. The result is a pointer to the complete object pointed to by expression. For example:

class A { ... };

class B { ... };

void f()
{
  A* pa = new A;
  B* pb = new B;
  void* pv = dynamic_cast<void*>(pa);
  // pv now points to an object of type A
  ...
  pv = dynamic_cast<void*>(pb);
  // pv now points to an object of type B
}

If type-id is not void*, a run-time check is made to see if the object pointed to by expression can be converted to the type pointed to by type-id.

If the type of expression is a base class of the type of type-id, a run-time check is made to see if expression actually points to a complete object of the type of type-id. If this is true, the result is a pointer to a complete object of the type of type-id. For example:

class B { ... };
class D : public B { ... };

void f()
{
  B* pb = new D;               // unclear but ok
  B* pb2 = new B;

  D* pd = dynamic_cast<D*>(pb);      // ok: pb actually points to a D
  ...
  D* pd2 = dynamic_cast<D*>(pb2);   //error: pb2 points to a B, not a D
                             // pd2 == NULL
  ...
}

This type of conversion is called a “downcast” because it moves a pointer down a class hierarchy, from a given class to a class derived from it.

dynamic_cast,它被用于安全地沿着类的继承关系向下进行类型转换。这就是说,你能用dynamic_cast把指向基类的指针或引用转换成指向其派生类或其兄弟类的指针或引用,而且你能知道转换是否成功。失败的转换将返回空指针(当对指针进行类型转换时)或者抛出异常(当对引用进行类型转换时)。

dynamic_casts在帮助你浏览继承层次上是有限制的。它不能被用于缺乏虚函数的类型上,也不能用它来转换掉constness。

4、reinterpret_cast Operator

MSDN:

The reinterpret_cast operator allows any pointer to be converted into any other pointer type. It also allows any integral type to be converted into any pointer type and vice versa. Misuse of the reinterpret_cast operator can easily be unsafe. Unless the desired conversion is inherently low-level, you should use one of the other cast operators.

Syntax

reinterpret_cast < type-id > ( expression )

The reinterpret_cast operator can be used for conversions such as char* to int*, or One_class* to Unrelated_class*, which are inherently unsafe.

The result of a reinterpret_cast cannot safely be used for anything other than being cast back to its original type. Other uses are, at best, nonportable.

The reinterpret_cast operator cannot cast away the const, volatile, or __unaligned attributes.

使用这个操作符的类型转换,其的转换结果几乎都是执行期定义(implementation-defined)。因此,使用reinterpret_casts的代码很难移植。 reinterpret_casts的最普通的用途就是在函数指针类型之间进行转换。

比如转换函数指针的代码是不可移植的(C++不保证所有的函数指针都被用一样的方法表示),在一些情况下这样的转换会产生不正确的结果(参见条款M31),所以你应该避免转换函数指针类型。

5、如果你使用的编译器缺乏对新的类型转换方式的支持,你可以用传统的类型转换方法代替static_cast, const_cast, 以及reinterpret_cast。也可以用下面的宏替换来模拟新的类型转换语法:
#define static_cast(TYPE,EXPR)          ((TYPE)(EXPR))
#define const_cast(TYPE,EXPR)          ((TYPE)(EXPR))
#define reinterpret_cast(TYPE,EXPR)   ((TYPE)(EXPR))

这些模拟不会象真实的操作符一样安全,但是当你的编译器可以支持新的的类型转换时,它们可以简化你把代码升级的过程。

没有一个容易的方法来模拟dynamic_cast的操作,但是很多函数库提供了函数,安全地在派生类与基类之间进行类型转换。如果你没有这些函数而你有必须进行这样的类型转换,你也可以回到C风格的类型转换方法上,但是这样的话你将不能获知类型转换是否失败。当然,你也可以定义一个宏来模拟dynamic_cast的功能,就象模拟其它的类型转换一样:

#define dynamic_cast(TYPE,EXPR)     (TYPE)(EXPR)

请记住,这个模拟并不能完全实现dynamic_cast的功能,它没有办法知道转换是否失败。

本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/wfwd/archive/2006/05/30/763785.aspx

cannot convert ‘this‘ pointer from ‘const ‘ to ‘ &‘ C++,error c2662 cannot convert 'this' pointer from 'const A' to 'A &' 阅读详情

相关推荐

C++ Convert 多种字符转换函数

C++ Convert 多种字符转换函数,网络上收集的多种整合, 自己看着选一个来用用就可以。 C++ Convert 多种字符转换函数,网络上收集的多种整合, 自己看着选一个来用用就可以。

转:关于C++中的类型转换

1、static_cast Operator MSDN: The expression static_cast ( expression ) converts expression to the type of type-id based solely on the types present in the expression. No run-time type check is made t

E.G的专栏 509

如何通过CAD图中的坐标来确定是哪个坐标系

地理坐标系:为球面坐标。参考平面地是椭球面,坐标单位:经纬度。以地球参考为例,坐标系就相当于整个地球,而地理坐标系就是椭球状的完整的立体地球。所以我们可以看到生活中的数据与地图是一定含有地理坐标系的,因为他是客观上来说确确实实存在的。投影坐标系:为平面坐标。参考平面地是水平面,坐标单位:米、千米等。这就相当于把地球当成一个橘子,然后一刀切开,把橘子皮平面铺开,这个过程就是地理投影的过程。严谨一点来说就是建立一个参考系统,按照对应位置把椭球体投射到平面。那坐标系统主要有那些呢?北京54。

vjmap的博客 2万+

C++之函数指针

[33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"? Yep. Consider the following function: int f(char a, float b); The type of this function is different dep

lxgwm2008的专栏 1278

3D Slicer-最强大的开源医学图像分割工具简要概述

3D Slicer 是一个免费的开源软件平台,用于医学、生物医学和其他 3D 图像的可视化、处理、分割、配准和分析。读/写DICOM图像和多种其他格式;三维图像、多边形网格和体积渲染的交互式可视化;手动编辑和标记图像;使用刚性和非刚性算法融合和共同配准数据;图像自动分割;跟踪图像引导程序的设备。所有的功能模块可在工具栏里找到,提供搜索,下拉选择,左右切换等功能。3D slicer的大概情况就介绍到这里。它的功能非常强大,也没有必要说掌握每个功能的使用。

Tina姐的博客 2万+

Workbench-nCode下发动机引擎应力疲劳分析

在工程数据库中定义材料模型参数,结构场分析基本参数:密度7850Kg/m3、弹性模量210E9Pa、泊松比0.3,疲劳分析参数:应力-疲劳曲线表(S-N Curve),应力-疲劳曲线如下图2所示,如果没有合适的数据可使用结构钢材料进行分析。网格为四面体高阶单元,各零件的单元尺寸如下表1所示,单元质量分布如下图3所示。在workbench平台下搭建分析流程如下图6所示,前述设定完成后,提交求解后即可得到相应的应力、应变结果,更新结果后目录树中会有相应的nCode DesignLife插件,如下图7所示。

ansysxuexizhe的博客 1548

C++之转换函数(convertion function)

目录一 类转换为其他类型二 double转换为Fraction 本文介绍一下C++的转换函数,例子是基于侯捷老师的关于一个分数类的例子,然后加上我自己的一些理解。 一 类转换为其他类型 类转换为其他类型,这里的其他类型可以是任何类型,如int、double甚至是你定义的一个类,至于怎么写,就是设计的人的事情了。 下面我以转换为double型为例,请看下面的例子: #include <iostream> #include <string> using namespace std;

weixin_43744293的博客 3018

OpenCV计算机视觉实战(12)——图像金字塔与特征缩放

图像金字塔技术通过对原始图像按不同分辨率进行多层次表示,不仅能提升计算效率,还能为图像融合、检测与识别提供多尺度特征。高斯金字塔 (Gaussian Pyramid) 用于构建多级低通图像,拉普拉斯金字塔 (Laplacian Pyramid) 则提取各层之间的细节信息。本节将深入介绍如何使用 OpenCV 构建高斯与拉普拉斯金字塔,并以经典的图像融合案例,展示图像金字塔在特征缩放与融合中的强大应用。

qq_30167691的博客 1404

C++修炼:C++中的类型转换

本文系统介绍了C++中的类型转换机制,主要内容包括:1. C语言类型转换回顾,包括隐式和显式转换;2. C++新增的类型转换特性,如内置类型与自定义类型间的转换(通过构造函数和operator函数实现);3. C++四种显式强制类型转换运算符:static_cast(常规转换)、reinterpret_cast(低级别转换)、const_cast(const属性操作)和dynamic_cast(多态类型安全转换);4. RTTI(运行时类型信息)机制及其应用。

但凡的博客 1008

华为OD机试真题 新系统2026-04-15 Java&Go 实现【小猫钓鱼纸牌游戏】

有两名玩家甲和乙,他们玩一种“小猫钓鱼”扑克牌游戏。扑克牌为A、2、3、....J、Q、K,不考虑花色都用1-13来表示,然后给甲,乙两人各发n张牌,按给定顺序排成队列,这些牌背面朝上,正面朝下放置,队列的第一个元素是背面的第一张牌。 游戏规则如下:

MISAYAONE的博客 354

07 Zabbix 微信告警

Zabbix 微信告警 1.注册企业微信 企业微信注册地址:https://work.weixin.qq.com 2.进入企业微信后台管理 2.1 添加微信成员 2.2创建应用 2.3 获取四项数据 (1)AgentID (2) Secret (3) 企业ID (4)部门ID 3.Zabbix Server配置 3.1确认脚本目录 # grep alertscripts /etc/zabbix/zabbix_server....

Jian Sun_的博客 1297

【C++】C++中的类型转换

标准C++为了加强类型转换的可视性,引入了四种命名的强制类型转换操作符:static_cast、reinterpret_cast、const_cast、dynamic_cast本文将向你详细的介绍他们的用途和使用方式。

weixin_45897952的博客 1125

RK3588平台开发系列讲解(USB篇)UAC初识

📢本篇将介绍RK3588平台`UAC`的配置使用。

内核笔记 3881
上一篇: VC++对象模型
下一篇: “域”的概念
yangfcf
博客等级 码龄19年 10粉丝 19原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值