为什么是“ Foo f(Bar());”?可以是采用Bar类型并返回Foo类型的函数的声明? [英] Why "Foo f(Bar());" can be a declaration of a function that takes type Bar and returns type Foo?
问题描述
我遇到了这个C ++问题:
I met this C++ question:
问题:以下是定义还是声明?
Question: Is the following a definition or a declaration?
Foo f(Bar());
答案:可能是函数声明为Bar类型并返回Foo类型,或者是 f
的定义,类型为 Foo
,其构造函数采用Bar类型。问题是两者的语法都相同,因此要解决此问题,C ++标准指出,在无法区分的情况下,编译器必须更喜欢函数声明而不是对象定义。
Answer: It is possibly either a declaration of a function that takes type Bar and returns type Foo or it is a definition of f
as a type Foo
, which has a constructor that takes type Bar. The problem is the syntax for both is identical so to resolve this problem the C++ standard states that a compiler must prefer function declarations to object definitions where it is unable to make a distinction.
-我不明白为什么它可以是声明Bar类型并返回Foo类型的函数的声明?括号()为何出现在参数列表中?
-- I don't understand why it can be "a declaration of a function that takes type Bar and returns type Foo"? how come a parenthesis "()" appear in parameter list?
推荐答案
函数 f
实际上将一个函数指针指向一个不带参数的函数,并给出一个 Bar
。 f
的参数类型为 Bar(*)()
。
The function f
actually takes a function pointer to a function that takes no arguments and gives a Bar
. The type of the argument to f
is Bar (*)()
.
此代码无法编译(我们可以在错误消息中看到参数的实际类型):
This code fails to compile (and we can see the actual type of the argument in the error message):
class Foo { };
class Bar { };
Foo f(Bar());
int main() {
Bar b;
f(b);
return 0;
}
但是此代码可以编译:
class Foo { };
class Bar { };
Foo f(Bar());
Bar g();
int main() {
f(g);
return 0;
}
正如您在问题中所说,它的第二个含义是您正在创建一个名为 f
的新的 Foo
对象,并使用 Bar( )
( Bar
的新实例)。类似于:
The second meaning it could have, as you say in the question, is that you are making a new Foo
object called f
and you are calling the constructor with Bar()
(a new instance of Bar
). It would be similar to:
Foo f = Foo(Bar());
在这种情况下 Foo f(Bar()); $
In this situation of Foo f(Bar());
though, the first interpretation is chosen by the compiler.
有些令人困惑的是,如果您添加另一组括号,例如
Somewhat confusingly, if you add another set of parentheses, as in
Foo f((Bar()));
编译器选择第二种解释。
the compiler picks the second interpretation.
这篇关于为什么是“ Foo f(Bar());”?可以是采用Bar类型并返回Foo类型的函数的声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!