为什么 Foo(b) 在 C++ 中编译成功?
Why does Foo(b) compile successfully in C++?
当我编译下面的代码时有一个奇怪的行为:
class Foo {
};
int main() {
Foo(b);
}
即使不声明b
也能编译成功。
有什么解释吗?
它本身就是一个声明。它声明了一个名为 b
且类型为 Foo
的变量,即与 Foo b;
.
相同的效果
There is an ambiguity in the grammar involving expression-statements and declarations: An expression-statement with a function-style explicit type conversion as its leftmost subexpression can be indistinguishable from a declaration where the first declarator starts with a (
. In those cases the statement is a declaration.
The remaining cases are declarations. [ Example:
class T {
// ...
public:
T();
T(int);
T(int, int);
};
T(a); // declaration
...
当我编译下面的代码时有一个奇怪的行为:
class Foo {
};
int main() {
Foo(b);
}
即使不声明b
也能编译成功。
有什么解释吗?
它本身就是一个声明。它声明了一个名为 b
且类型为 Foo
的变量,即与 Foo b;
.
There is an ambiguity in the grammar involving expression-statements and declarations: An expression-statement with a function-style explicit type conversion as its leftmost subexpression can be indistinguishable from a declaration where the first declarator starts with a
(
. In those cases the statement is a declaration.
The remaining cases are declarations. [ Example:
class T { // ... public: T(); T(int); T(int, int); }; T(a); // declaration
...