C++嵌套构造函数调用与函数声明
以下代码部分中标记为“版本 1”和“版本 2”的代码片段有什么区别:
int main() {
using namespace std;
typedef istream_iterator<int> input;
// version 1)
//vector<int> v(input(cin), input());
// version 2)
input endofinput;
vector<int> v(input(cin), endofinput);
}
据我了解,“版本 1”被视为函数声明。但我不明白为什么,也不明白返回类型为 vector
的结果函数 v
的参数是什么。
What is the difference between the code snippets labeled "version 1" and "version 2" in the following code section:
int main() {
using namespace std;
typedef istream_iterator<int> input;
// version 1)
//vector<int> v(input(cin), input());
// version 2)
input endofinput;
vector<int> v(input(cin), endofinput);
}
As far as I understand "version 1" is treated as function declaration. But I don't understand why nor what the arguments of the resulting function v
with return type vector<int>
are.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为标准或多或少地说,任何可能被解释为函数声明的东西都将在任何上下文中,无论如何。
你可能不相信这一点,但这是真的。
input(cin)
被视为输入 cin
;在这个地方,括号是允许的,但毫无意义。但是,input()
不会被视为声明没有名称的input
类型的参数;相反,它是一个input(*)()
类型的参数,即指向不带参数并返回input
的函数的指针。显然,(*) 部分在声明类型时是不必要的。我猜出于同样的原因,当您使用函数名称来初始化函数指针时,&
是可选的......另一种解决此问题的方法是利用我们声明的事实无论如何,单独的值来证明跳过 typedef 是合理的:
另一种方法是以函数声明不允许的方式添加括号:
有关更多信息,Google“c++ 最令人烦恼的解析”。
Because the Standard says, more or less, that anything that can possibly be interpreted as a function declaration will be, in any context, no matter what.
You might not believe this, but it's true.
input(cin)
is treated asinput cin
; in this spot, parentheses are allowed and simply meaningless. However,input()
is not treated as declaring a parameter of typeinput
with no name; instead, it is a parameter of typeinput(*)()
, i.e. a pointer to a function taking no arguments and returning aninput
. The (*) part is unnecessary in declaring the type, apparently. I guess for the same reason that the&
is optional when you use a function name to initialize the function pointer...Another way to get around this, taking advantage of the fact that we're declaring the values separately anyway to justify skipping the typedef:
Another way is to add parentheses in a way that isn't allowed for function declarations:
For more information, Google "c++ most vexing parse".
这被称为最令人烦恼的解析:
这个片段:
可以作为
大多数程序员期望第一个,但 C++ 标准要求将其解释为第二个。
This is called most vexing parse :
This snippet :
could be disambiguated either as
Most programmers expect the first, but the C++ standard requires it to be interpreted as the second.
好吧,这个函数声明的参数如下:
input(cin)
- 这是一个对象input (*)()
- 这是一个指向返回函数的指针>输入
并且不接受任何参数。Well, the arguments to this function declaration are these:
input(cin)
- which is an objectinput (*)()
- which is a pointer to function returninginput
and taking no argument.