了解 C++编译器
我遇到了这个简单的 C++ 问题,这让我想重新开始我的计算机科学学位,试图这次学习一些东西。 ;)
为什么这段代码不能编译:
vector<int> v(int());
v.push_back(1);
而另一个编译时没有任何警告,
vector<int> v((int()));
v.push_back(1);
甚至很难找到差异(添加了额外的括号:P)。
Possible Duplicate:
Most vexing parse: why doesn't A a(()); work?
I am having this simple C++ issue that is making me wanna restart my CS degree all over again trying to learn something this time. ;)
Why this code doesn't compile:
vector<int> v(int());
v.push_back(1);
while this other one compiles without a single warning
vector<int> v((int()));
v.push_back(1);
It's even hard to find a difference at all (extra parenthesis were added :P).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这被称为最令人烦恼的解析。
声明一个函数。
v
,它接受一个函数(不接受返回int
的参数)并返回一个vector
。这会自动“调整”为函数v
,该函数采用指向函数的指针(不采用返回int
的参数)并返回 <代码>向量额外的一对括号会抑制这种解释,因为您不能在函数声明中的参数声明符周围放置额外的括号,因此
(int())
只能解释为名为v 的对象的初始值设定项
。C++ 有一个明确的消歧规则,如果它具有句法(但不一定是语义)意义,则更愿意将事物(在本例中为
int()
)解析为声明符而不是表达式。It's called the most vexing parse.
Declares a function
v
that takes a function (taking no parameters returning anint
) and returns avector<int>
. This is automatically "adjusted" to a functionv
that takes a pointer to a function (taking no parameters returning anint
) and returns avector<int>
.The extra pair of parentheses inhibits this interpretation as you can't place extra parentheses around parameter declarators in function declarations so
(int())
can only be interpreted as an initializer for an object namedv
.C++ has an explicit disambiguation rule that prefers to parse things (in this case
int()
) as declarators rather than expressions if it makes syntactic (but not necessarily semantic) sense.实际上它是一个函数声明。请参阅:http://www.gotw.ca/gotw/075.htm
Indeed its a function declaration. See: http://www.gotw.ca/gotw/075.htm