我有一个基类,该基类在以下头文件中声明:
#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 {
答案 0 :(得分:2)
根据this的答案#pragma once
有无法修复的错误。永远不要使用它。
您可以使用下面的标题保护器
#ifndef HEADER_H
#define HEADER_H
// Header file code
#endif
答案 1 :(得分:0)
#pragma once
不是一个标准,即使许多编译器都支持它,也不应该使用#ifndef
保护头文件。由于#pragma一次没有标准行为,因此您不应该假定该行为在所有编译器上都相同。