C ++嵌套构造函数调用与函数声明 [英] C++ nested constructor calls vs. function declaration
问题描述
以下代码段中标记为版本1和版本2的代码段有什么区别:
int main(){
using namespace std;
typedef istream_iterator< int>输入;
//版本1)
// vector< int> v(input(cin),input());
//版本2)
输入endofinput;
vector< int> v(输入(cin),endofinput);
}
据我所知,版本1被视为函数声明。但我不明白为什么以及返回类型 vector< int>
的结果函数 v
的参数是。
为什么
因为标准或多或少地说,任何可能被解释为函数声明的东西在任何情况下都是无论如何。
< blockquote>
什么是参数...
您可能不会相信这一点,但这是事实。 input(cin)
被视为输入cin
;在这一点上,括号是允许的,而且毫无意义。但是, input()
不被视为声明不带名称的类型 input
的参数。相反,它是 input(*)()
类型的参数,即指向不带参数并返回输入
。显然,(*)部分在声明类型时是不必要的。我猜是出于同样的原因,当你使用函数名来初始化函数指针时,&
是可选的...
另一种解决此问题的方法是,利用我们无论如何都分别声明值的事实,以证明跳过typedef:
istream_iterator< INT>开始(cin),结束;
vector< int> v(开始,结束);
另一种方法是以不允许用于函数声明的方式添加圆括号:
vector< int> v((input(cin)),input());
有关更多信息,请参阅Googlec ++最令人头疼的解析。
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.
why
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.
what the arguments... are
You might not believe this, but it's true. input(cin)
is treated as input cin
; in this spot, parentheses are allowed and simply meaningless. However, input()
is not treated as declaring a parameter of type input
with no name; instead, it is a parameter of type input(*)()
, i.e. a pointer to a function taking no arguments and returning an input
. 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:
istream_iterator<int> start(cin), end;
vector<int> v(start, end);
Another way is to add parentheses in a way that isn't allowed for function declarations:
vector<int> v((input(cin)), input());
For more information, Google "c++ most vexing parse".
这篇关于C ++嵌套构造函数调用与函数声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!