考虑下面的代码:
struct Foo {
struct Bar;
Foo()
{
Bar bar; // Why isn't Bar an incomplete type?!
}
struct Bar {}; // Full definition
};
// struct Bar {}; // fails to compile due to incomplete type
int main()
{
Foo foo;
}
它在至少 2 个编译器(gcc5.2、clang3.5)下编译得很好。我的问题是:
- 为什么
Bar
在构造函数Foo::Foo
中不被视为不完整类型,因为我在构造函数上方将其前向声明,但在构造函数内部完全使用它?
每当我将 Foo::Bar
移出类,换句话说 Bar
成为一个独立的类时,我都会得到预期的
error: aggregate 'Foo::Bar bar' has incomplete type and cannot be defined
最佳答案
在成员规范中,类在函数体中被认为是完整的,来自草案 C++ 标准部分 9.2
[class.mem]:
A class is considered a completely-defined object type (3.9) (or complete type) at the closing } of the class-specifier. Within the class member-specification, the class is regarded as complete within function bodies, default arguments, using-declarations introducing inheriting constructors (12.9), exception-specifications, and brace-or-equal-initializers for non-static data members (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification
这意味着您甚至不必转发声明 Bar
( see it live ):
struct Foo {
Foo()
{
Bar bar;
}
struct Bar {};
};
前向声明有助于避免违反 3.3.7 paragraph 2 and 3 部分.
关于c++ - 为什么内联声明不是不完整的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32685319/