C++: Has Not Been Declared

大兔子大兔子 提交于 2019-11-27 19:20:44

问题


I have seen this type of error everywhere and, although I have looked at the answers, none seem to help.

I get the following error with the following piece of code:

error: 'A' has not been declared

B.h:

#include "A.h"
class B{
    public:
         static bool doX(A *a);
};

A.h:

include "B.h"
class A{};

To run off a checklist of things I've already tried: - Names are spelled correctly - A is in A.h - There are no namespaces - No templates - No macros

I have other classes with can find A just fine. The only thing I can think of is that 'static' is causing a problem.


回答1:


Replace the include with a forward declaration:

//B.h
class A;
class B{
    public:
         static bool doX(A *a);
};

Include files only when you have to.

Also, use include guards. This will prevent other nasty issues like re-definitions & such.




回答2:


If you have two headers including each other you end up with a circular dependency, and due to the way the preprocessor works it means one will be defined before the other.

To fix, I would avoid including A.h in B.h, and just forward declare instead:

class A;
class B{
    public:
         static bool doX(A *a);
};

You can then include A.h in B.cpp



来源:https://stackoverflow.com/questions/14084826/c-has-not-been-declared

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!