(类型)值和类型(值)之间的区别是什么? [英] What is the difference between (type)value and type(value)?

查看:136
本文介绍了(类型)值和类型(值)之间的区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之间有什么区别

 (type)value 

  type(value)



在C ++中?

解决方案

没有区别;按照标准(§5.2.3):


简单类型说明符(7.1.5)后跟括号表达式列表构造一个值给定表达式列表的指定类型。如果表达式列表是单个表达式,则类型转换表达式与相应的强制转换表达式(5.4)是等效的(在定义中,如果定义的话)。

由于问题指定 type(value) (类型)值,这绝对没有区别。



如果且仅当处理逗号分隔的的值可以有差异。在这种情况下:


如果表达式列表指定多个单一值,则该类型应为一个具有适当声明的构造函数(8.5,12.1) ,并且表达式T(x1,x2,...)在效果上等效于声明T t(x1,x2,...);对于一些发明的临时变量t,结果是t的值作为右值。

正如Troubadour指出的,有一些类型的类型(值)版本根本不会编译。例如:

  char * a =(char *)string; 

将编译,但:

  char * a = char *(string); 

不会。具有不同名称(例如,用 typedef 创建)的相同类型可以工作:

  typedef char * char_ptr; 

char * a = char_ptr(string);


What is the difference between

(type)value

and

type(value)

in C++?

解决方案

There is no difference; per the standard (§5.2.3):

A simple-type-specifier (7.1.5) followed by a parenthesized expression-list constructs a value of the specified type given the expression list. If the expression list is a single expression, the type conversion expression is equivalent (in definedness, and if defined in meaning) to the corresponding cast expression (5.4).

Since the question specified the difference between type(value) and (type)value, there is absolutely no difference.

If and only if you're dealing with a comma-separated list of values can there be a difference. In this case:

If the expression list specifies more than a single value, the type shall be a class with a suitably declared constructor (8.5, 12.1), and the expression T(x1, x2, ...) is equivalent in effect to the declaration T t(x1, x2, ...); for some invented temporary variable t, with the result being the value of t as an rvalue.

As Troubadour pointed out, there are a certain names of types for which the type(value) version simply won't compile. For example:

char *a = (char *)string;

will compile, but:

char *a = char *(string);

will not. The same type with a different name (e.g., created with a typedef) can work though:

typedef char *char_ptr;

char *a = char_ptr(string);

这篇关于(类型)值和类型(值)之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆