命名空间问题:前向声明和混合命名空间

Namespace questions: forward declaration and mixing namespaces

我对 C++ 不是很熟悉,这是我第一次不仅仅使用命名空间 std。以下有什么区别?

using MyNameSpace::MyClass;

namespace MyNameSpace {class MyClass;}

两者之后,我现在似乎可以创建一个 MyClass 对象。一种方法比另一种更好吗?另外,如果我不这样做,我仍然可以通过在每次需要时在它前面附加 MyNameSpace::MyClass 来引用 MyClass 吗?

接下来,如果我使用第二个选项转发声明,我还需要#include "MyClass.h"吗?以我(不是很好)的理解,在 C++ 中,您制作头文件是为了转发声明 类 以便以后可以使用它们。那么如果你已经前向声明了,还需要包含头文件吗?

最后,当使用多个名称空间(namespace Architecturenamespace Router)时,我有一个错误我不知道如何解释。在我的一个头文件中,我将 using std::vector 作为 #include 语句之后的第一行。我认为这个声明不在任何命名空间内。编译时,我收到错误消息“'Architecture::std::vector' 尚未声明”。为了解决这个问题,我可以将语句更改为 using ::std::vector 以告诉它查看 std::vector.

的全局范围

但是,我不明白为什么会出现这个问题。因为我在头文件的顶部声明 using std::vector,为什么我还没有在全局范围内?一个更好的问题可能是:我如何知道我在头文件顶部的范围?此外,我认为在 C++ 中(根据这个答案What is the difference between writing "::namespace::identifier" and "namespace::identifier"?),如果在当前范围内找不到名称,您会自动查找一个级别,直到到达全局范围。

我希望这些问题写得很好并且可以理解。希望我能得到这些问题的一些答案,并开始了解命名空间如何相互交互。

using MyNameSpace::MyClass;

这个 using-declaration 将名称 MyClass 注入当前作用域,引用 MyNameSpace::MyClass 表示的实体,这一定是先前声明。

namespace MyNameSpace {class MyClass;}

这是命名空间 MyNamespace.

中 class MyClass 的前向声明

After both, it seems I can now create a MyClass object.

第二种情况不太可能,除非您有 using namespace MyNamespace; 并且 MyClass 的完整定义可用。

Is one way better than the other?

他们做完全不同的事情。

Also, if I don't do either, can I still reference MyClass by appending MyNameSpace::MyClass before it every time I need to?

如果 using MyNameSpace::MyClass; 编译(即,MyNameSpace::MyClass 已被声明),那么你可以这样做。否则,你不能。

Next, if I forward declare using the second option, do I still need to #include "MyClass.h"? In my (not very good) understanding, in C++, you make header files in order to forward declare classes so that they can be used later. So if you have already forward declared, would you still need to include the header file?

Headers 通常带有完整的 class 定义——包括所有数据成员和成员函数的声明。像 class MyClass; 这样的前向声明不允许您创建 MyClass object,因为编译器不知道要为 object 分配多少内存或有哪些构造函数可用.

However, I don't understand why this problem exists. Since I am declaring using std::vector at the top of my header file, why am I not already at global scope? A better question might be: how can I tell which scope I am in at the top of a header file? Additionally, I thought in C++ (and according to this answer What is the difference between writing "::namespace::identifier" and "namespace::identifier"?, if you couldn't find the name within the current scope, you would automatically look up a level until you reach global scope.

这听起来像是缺少大括号的问题。如果您编写的 header 没有关闭 namespace Architecture,那么您在 header 之后包含的任何内容都将被意外放入 Architecture 命名空间。如果这不是问题,请 post a MCVE.