gpt4 book ai didi

c++ - 成员的结构与命名空间的潜在范围

转载 作者:太空狗 更新时间:2023-10-29 20:01:55 27 4
gpt4 key购买 nike

引用这段代码:

namespace Y {
char f() { return y; } // error: y was not declared in this scope
char y;
}

struct X {
char f() { return x; } // OK
char x;
};

根据 basic.scope.namespace#1 :

The declarative region of a namespace-definition is its namespace-body. Entities declared in a namespace-body are said to be members of the namespace, and names introduced by these declarations into the declarative region of the namespace are said to be member names of the namespace. Its potential scope includes its namespace from the name's point of declaration onwards.

问题

  1. 错误是由于 Y::y 尚未在 Y::f() 中声明而造成的,这样说是否正确?

  2. 我不明白为什么 namespace 成员在声明期间没有“重新排序”,而 struct是。禁止这种行为的原因可能是什么? 标准是否有类似的说法?

最佳答案

Is it correct to say that the error was due to the fact that Y::y is not yet declared in Y::f()?

是的。

I can't figure why there isn't a "reodering" for namespace members during declaration while for struct there is. What could be the reason for disallowing such behavior? Does the standard says something similar?

与类相比,命名空间的最大障碍是它们永远不会“关闭”。您始终可以通过在另一个翻译单元中重新打开命名空间并在其中声明更多内容来将成员添加到命名空间。然而,一个类声明,对于它的所有成员,必须完全出现在一个翻译单元中。并且以后没有添加。

[class.mem]/1

The member-specification in a class definition declares the full set of members of the class; no member can be added elsewhere.

命名空间的问题很棘手。但是类(class)只需要多一点,非常本地化的工作。

因此,对于语言设计者和编译器编写者来说,要求命名空间声明在使用之前出现要容易得多。

您还应该注意,您只能在定义内的一组特定位置使用该类的其他成员。

[class.mem]/6

A class is considered a completely-defined object type ([basic.types]) (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, noexcept-specifiers, and default member initializers (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification.

关于c++ - 成员的结构与命名空间的潜在范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49852641/

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