其他命名空间中的对象没有包含,否则文件相同

Objects in other namespace not found without include, files otherwise identical

本文关键字:文件 包含 命名空间 对象 其他      更新时间:2023-10-16

我有两个功能相同的头文件,其中一个无缘无故地产生错误。我在创建新的(损坏的)文件时一定做错了什么,但我无法弄清楚是什么。

我的IDE是Xcode。该项目是使用 Apple LLVM Compiler 4.1 针对 Objective C++ 编译的,但有问题的代码部分都是纯C++,没有 Objective C。

下面是一些代码:

命名空间A.Common.h

#include "../NamespaceB/Common.h"
#include "WorkingClass.h"
#include "BrokenClass.h"
...

../NamespaceB/Common.h

#ifndef NamespaceBCommon
#define NamespaceBCommon
namespace NamespaceB
{
...
}
...
#include "Superclass.h"
...

工人阶级.h

#ifndef NamespaceA_WorkingClass
#define NamespaceA_WorkingClass
namespace NamespaceA
{
class WorkingClass : public NamespaceB::Superclass
{
public:
WorkingClass();
~WorkingClass();
};
}
#endif

破碎的类.h

#ifndef NamespaceA_BrokenClass
#define NamespaceA_BrokenClass
// If I don't have this line I get errors. Why??                   !!!!!
// This file is exactly identical to WorkingClass.h 
// as far as I can tell!
//#include NamespaceA.Common.h
namespace NamespaceA
{            
// Parse Issue: Expected class name                            !!!!!
// Semantic Issue: Use of undeclared identifier 'NamespaceB'
class BrokenClass : public NamespaceB::Superclass
{
public:
BrokenClass();
~BrokenClass();
};
}
#endif

谢谢。

需要包含代码中引用的命名空间和类的所有文件。因此,由于您在BrokenClass.h中引用了NamespaceB::Superclass,因此需要确保包含声明该文件的文件。在这种情况下,包含NamespaceA.Common.h(希望)可以解决此问题,因为它包含包含NamespaceB的文件。

至于为什么你不必在你的WorkingClass.h中包含NamespaceA.Common.h,我怀疑这是因为你碰巧在其他地方包含了../NamespaceB/Common.h

我发现了问题。WorkingClass.cpp包括NamespaceA.Common.h而不是包括自己的头文件,而不是在头中包含通用文件,然后在 cpp 中包含自己的头文件。

我设法错过了WorkingClass.cpp#include,因为我只是认为它只包括WorkingClass.h而不是NamespaceA.Common.h

简而言之:

工人阶级.h

// Class goes here
// No includes

工人阶级.cpp

// Notice it does not include WorkingClass.h for whatever reason
#include "NamespaceA.Common.h"

命名空间A.Common.h

#include "../NamespaceB/Common.h"
#include "WorkingClass.h"
#include "BrokenClass.h"
#include "EveryOtherClass.h" ...

破碎的类.h

// Class goes here
// No includes

破碎类.cpp

#include "BrokenClass.h"
// Oh no! Where's NamespaceA.Common.h?

我不是这个包含方案的忠实粉丝,但我会接受它,因为这是一个我不想进行彻底更改的大型项目。