gpt4 book ai didi

c++ - 内部成员在类里面的可见性

转载 作者:可可西里 更新时间:2023-11-01 15:21:25 36 4
gpt4 key购买 nike

根据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

所以,下面的代码应该可以编译,而且确实可以编译

struct Foo{
Foo()
{
Bar bar; // Bar is fully visible here, even though it's defined later
}
//void f(Bar){} // But NOT VISIBLE if used as a function parameter
struct Bar{};
};

int main()
{
Foo foo;
}

Live on Coliru

但是,如果我取消注释定义成员函数 void Foo::f(Bar) 的行,则代码无法编译并出现错误

error: 'Bar' has not been declared

再次阅读标准,似乎函数参数确实不被视为类被视为完整的地方。但是,它根本没有任何意义。你能解释一下为什么我不能在函数参数中使用 Bar(但可以在 inside 函数中完全使用它而没有任何问题)在它的完整定义之前吗?

最佳答案

9.2 [class.mem] 中列出的所有情况下,可以推迟知道类型,直到类被完全定义。我们可以在 defect report 643: Use of decltype in a class member-specification 中看到这个理由其中说:

In the other cases where a class type is considered complete within the definition of the class, it is possible to defer handling the construct until the end of the definition. That is not possible for types, as the type may be needed immediately in subsequent declarations.

作为 T.C.指出还涉及查找问题 defect report 325: When are default arguments parsed?defect report 1352处理。后者还提到了能够将解析延迟到类(class)完成的相同技术:

The rules regarding class scope and when the class is considered to be complete (normally implemented by deferred parsing of portions of class member declarations) are inconsistent and need to be clarified.

关于c++ - 内部成员在类里面的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33907864/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com