What is the difference between (type)value and 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) 有什么区别?


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01