问题包括所有子标题中的基本标题

时间:2018-10-08 11:42:20

标签: c++ inheritance compiler-errors include

我有一个基类,该基类在以下头文件中声明:

#pragma once
#include "StateHandler.hpp"

namespace ta {
    class GameState {
    public:
        // ...
    };
} /* ta */

然后,我有两个孩子,看起来像这样:

#pragma once
#include "../GameState.hpp"

namespace ta {
    class DefaultState: public ta::GameState {
    public:
        // ...
    };
} /* ta */

#pragma once
#include "../GameState.hpp"

namespace ta {
    class WorldMapState: public ta::GameState {
    public:
        // ...
    };
} /* ta */

当尝试编译该代码时,出现错误,即GameState没有在我包含的两个子代中的第二个中声明。当我从#pragma once中删除GameState.hpp时,它说GameSate被重新定义。我知道为什么会这样,但是我找不到解决该问题的方法。

更新:使用include-guards也不起作用。使用#pragma once或include-guards时出现以下错误:

In file included from /[...]/include/statemachine/gamestates.hpp:2,
                 from /[...]/include/common.hpp:4,
                 from /[...]/include/statemachine/gamestates/../StateHandler.hpp:5,
                 from /[...]/include/statemachine/gamestates/../GameState.hpp:4,
                 from /[...]/include/statemachine/gamestates/DefaultState.hpp:4,
                 from /[...]/include/statemachine/gamestates.hpp:1,
                 from /[...]/include/common.hpp:4,
                 from /[...]/source/main.cpp:1:
/[...]/include/statemachine/gamestates/WorldMapState.hpp:7:47: error: expected class-name before '{' token
     class WorldMapState: public ta::GameState {
                                               ^

这是我在#pragma once中不使用include-guards或GameState.hpp时遇到的错误(此错误出现3次):

In file included from /[...]/include/common.hpp:5,
                 from /[...]/source/main.cpp:1:
/[...]/include/statemachine/GameState.hpp:4:11: error: redefinition of 'class ta::GameState'
     class GameState {
           ^~~~~~~~~
In file included from /[...]/include/statemachine/gamestates/WorldMapState.hpp:4,
                 from /[...]/include/statemachine/gamestates.hpp:2,
                 from /[...]/include/common.hpp:4,
                 from /[...]/include/statemachine/gamestates/../StateHandler.hpp:5,
                 from /[...]/include/statemachine/gamestates/../GameState.hpp:1,
                 from /[...]/include/statemachine/gamestates/DefaultState.hpp:4,
                 from /[...]/include/statemachine/gamestates.hpp:1,
                 from /[...]/include/common.hpp:4,
                 from /[...]/source/main.cpp:1:
/[...]/include/statemachine/gamestates/../GameState.hpp:4:11: note: previous definition of 'class ta::GameState'
     class GameState {

2 个答案:

答案 0 :(得分:2)

根据this的答案#pragma once有无法修复的错误。永远不要使用它。
您可以使用下面的标题保护器

#ifndef HEADER_H
#define HEADER_H

// Header file code

#endif

答案 1 :(得分:0)

#pragma once不是一个标准,即使许多编译器都支持它,也不应该使用#ifndef保护头文件。由于#pragma一次没有标准行为,因此您不应该假定该行为在所有编译器上都相同。