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

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

问题描述

有什么区别

(类型)值

类型(值)

在 C++ 中?

解决方案

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

<块引用>一个简单类型说明符(7.1.5)后跟一个带括号的表达式列表构造一个给定表达式列表的指定类型的值.如果表达式列表是单个表达式,则类型转换表达式等效于(在定义上,并且如果在含义上定义)对应的强制转换表达式(5.4).

由于题中指定了type(value)(type)value的区别,所以绝对没有区别.

当且仅当您处理以逗号分隔的 list 值时,才会有区别.在这种情况下:

<块引用>如果表达式列表指定了多个值,则类型应为具有适当声明的构造函数(8.5、12.1)的类,并且表达式 T(x1, x2, ...) 在效果上等同于声明 T t(x1, x2, ...);对于某些发明的临时变量 t,其结果是将 t 的值作为右值.

正如 Troubadour 指出的那样,type(value) 版本根本无法编译某些类型的名称.例如:

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天全站免登陆