(类型)值和类型(值)有什么区别?(What is the difference between (type)value and type(value)?)

编程入门 行业动态 更新时间:2024-10-23 11:31:37
类型)值和类型(值)有什么区别?(What is the difference between (type)value and type(value)?)

有什么区别?

(type)value

type(value)

在C ++中?

What is the difference between

(type)value

and

type(value)

in C++?

最满意答案

没有区别 根据标准(§5.2.3):

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

由于问题指定了type(value)和(type)value之间的差异,绝对没有区别。

当且仅当您处理逗号分隔的值列表时 ,才有区别。 在这种情况下:

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

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

char *a = (char *)string;

将编译,但:

char *a = char *(string);

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

typedef char *char_ptr; char *a = char_ptr(string);

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);

更多推荐

本文发布于:2023-07-04 10:58:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1023546.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   有什么区别   type   difference

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!