了解 C++编译器

发布于 2024-12-28 11:23:19 字数 477 浏览 2 评论 0原文

可能的重复:
最令人烦恼的解析:为什么不 A a(());工作?

我遇到了这个简单的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

转瞬即逝 2025-01-04 11:23:19

这被称为最令人烦恼的解析。

vector<int> v(int());

声明一个函数 v,它接受一个函数(不接受返回 int 的参数)并返回一个 vector。这会自动“调整”为函数 v,该函数采用指向函数的指针(不采用返回 int 的参数)并返回 <代码>向量

额外的一对括号会抑制这种解释,因为您不能在函数声明中的参数声明符周围放置额外的括号,因此 (int()) 只能解释为名为 v 的对象的初始值设定项

C++ 有一个明确的消歧规则,如果它具有句法(但不一定是语义)意义,则更愿意将事物(在本例中为 int())解析为声明符而不是表达式。

It's called the most vexing parse.

vector<int> v(int());

Declares a function v that takes a function (taking no parameters returning an int) and returns a vector<int>. This is automatically "adjusted" to a function v that takes a pointer to a function (taking no parameters returning an int) and returns a vector<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 named v.

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.

半世蒼涼 2025-01-04 11:23:19

实际上它是一个函数声明。请参阅:http://www.gotw.ca/gotw/075.htm

Indeed its a function declaration. See: http://www.gotw.ca/gotw/075.htm

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文