命名空间“bar”中的“Foo”没有为头文件中的对象成员命名类型

Mae*_*edy 1 c++ eclipse-cdt c++11

作为前言,我使用 eclipse c++ 作为 IDE。我使用的是 c++ 0x 11 标准。(所以我可以使用互斥锁)我对 C++ 很陌生,但以前做过一些 C 并且非常熟悉 Java 编程。另外,我知道 .h 通常不是 C++ 文件的类型。

我试图在我的类 stlad::Dispatcher 中包含 stlad::KeyHook 的私有对象成员,并且在构建时出现以下错误:

Building file: ../src/KeyHook.cpp
Invoking: GCC C++ Compiler
g++ -std=c++0x -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/KeyHook.d" -MT"src/KeyHook.d" -o "src/KeyHook.o" "../src/KeyHook.cpp"
In file included from ../src/KeyHook.h:10:0,
                 from ../src/KeyHook.cpp:8:
../src/Dispatcher.h:23:11: error: ‘KeyHook’ in namespace ‘stellad’ does not name a type
  stellad::KeyHook keyhook;
           ^
src/subdir.mk:21: recipe for target 'src/KeyHook.o' failed
make: *** [src/KeyHook.o] Error 1
Run Code Online (Sandbox Code Playgroud)

许多行已被删除以减少噪音,例如不必要的包含、原型和函数声明。

调度员.h

/*
 * Dispatcher.h
 */

#ifndef DISPATCHER_H_
#define DISPATCHER_H_

#include "KeyHook.h"

namespace stellad {

class Dispatcher {
private:
    ..
    stellad::KeyHook keyhook;
public:
    Dispatcher();
    virtual ~Dispatcher();
    ..
};

} /* namespace stellad */

int main(int argc, const char* argv[]);
#endif /* DISPATCHER_H_ */
Run Code Online (Sandbox Code Playgroud)

密钥钩子文件

/*
 * KeyHook.h
 */

#ifndef KEYHOOK_H_
#define KEYHOOK_H_
#include "Dispatcher.h"

namespace stellad {

class KeyHook{
private:
    ..

public:
    KeyHook();
    virtual ~KeyHook();
    ..
};


} /* namespace stellad */

#endif /* KEYHOOK_H_ */
Run Code Online (Sandbox Code Playgroud)

Ste*_*oft 6

它是由包括另一个文件在内的每个文件引起的。

如果第一个包含的是KeyHook.h,则在它包含的任何声明之前Dispatcher.h。这KeyHook.h再次包括但它发现KEYHOOK_H_已经定义并且没有声明任何内容。然后标题看起来像这样:

// #include "KeyHook.h" from KeyHook.cpp
// #define KEYHOOK_H_

// #include "Dispatcher.h" from KeyHook.h
// #define DISPATCHER_H_

// #include "KeyHook.h" from Dispatcher.h
// KEYHOOK_H_ already declared
// end of #include "KeyHook.h" from Dispatcher.h

namespace stellad {

class Dispatcher {
private:
    ..
    stellad::KeyHook keyhook; // KeyHook not declared here
public:
    Dispatcher();
    virtual ~Dispatcher();
    ..
};

} /* namespace stellad */

int main(int argc, const char* argv[]);

// end of #include "Dispatcher.h" from KeyHook.h

namespace stellad {

class KeyHook{
private:
    ..

public:
    KeyHook();
    virtual ~KeyHook();
    ..
};

} /* namespace stellad */
Run Code Online (Sandbox Code Playgroud)

要解决这个问题,您需要打破循环包含。KeyHook不需要Dispatcher,只需#include "Dispatcher.h"从中删除即可。