gpt4 book ai didi

c++ - 函数样式转换与调用构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:14:04 26 4
gpt4 key购买 nike

如果我有一个类 A,并且我写了 A(5);,它显然是一个临时变量。

但是不清楚 A(5); 是构造函数调用(使用 5 作为参数),还是函数样式转换,转换 5A。有人可以给我解释一下吗?

最佳答案

这是一种函数式类型转换,它创建了一个 t来自 int通过调用构造函数。在 C++ 中无法显式调用构造函数。

这在 [expr.type.conv] 中有描述(N3337):

5.2.3 Explicit type conversion (functional notation)

1) A simple-type-specifer (7.1.6.2) or typename-specifer (14.6) 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). If the type specified is a class type, the class type shall be complete. 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 a prvalue.

t是一个简单类型说明符,这等同于相应的强制转换表达式。这允许执行相当于 static_cast 的操作。 ( [expr.cast]/4 ),它定义了转换的最终结果:

[expr.static.cast]/4: Otherwise, an expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed, for some invented temporary variable t (8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion. The expression e is used as a glvalue if and only if the initialization uses it as a glvalue.

关于c++ - 函数样式转换与调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37255200/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com