0

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

我的 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"

...

../命名空间B/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

谢谢你。

4

2 回答 2

1

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

至于为什么您不必包含NamespaceA.Common.h在您的 WorkingClass.h 中,我怀疑这是因为您恰好../NamespaceB/Common.h包含在其他地方。

于 2012-10-26T02:23:08.073 回答
0

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

我设法错过了#includeWorkingClass.cpp因为我只是假设它只是包括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?

我不是这个包含方案的忠实拥护者,但我会接受它,因为它是一个大型项目,我不想对其进行彻底的改变。

于 2012-10-26T02:41:04.510 回答