(type)value 和 type(value) 有什么区别?

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

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

问题描述

有什么区别

(类型)值

类型(值)

在 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 的值作为右值.

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

这篇关于(type)value 和 type(value) 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:(type)value 和 type(value) 有什么区别?

基础教程推荐