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

标签 c++ scope namespaces declaration

引用这段代码:

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/

相关文章:

c++ - 使用 lambda 填充 vector 以确定索引是偶数还是奇数

c++ - 右值引用是否有reference_wrapper<>?

javascript - 提升没有声明为 'var' 的 JS 变量

c# - 在其他项目中使用命名空间

c++ - 如何访问指针数组中字符串的各个元素?

c++ - 调用祖 parent 构造函数的虚拟但不是多重继承

javascript - Jquery $.post() 变量作用域

ruby-on-rails - Ruby on Rails 中 db/seeds.rb 中的代码范围是什么?

asp.net - 将命名空间添加到现有项目 ASP.NET 2.0 C#

c++ - if 命名空间内的语句给出错误