我有一个基类,它在下面的头文件中声明:
#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没有在我包含的两个孩子中的第二个中声明。当我从GameState.hpp中删除#pragma once时,它告诉我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 {
^这是我在GameState.hpp中没有使用include-guards或#pragma once时得到的错误(这个错误出现了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 {发布于 2018-10-08 19:50:29
根据this answer的说法,#pragma once有无法修复的错误。它永远不应该被使用。
您可以使用标题保护,如下所示
#ifndef HEADER_H
#define HEADER_H
// Header file code
#endif发布于 2018-10-08 19:50:27
#pragma once不是一个标准,即使它被许多编译器支持,也不应该用来保护头文件,而应该使用#ifndef。因为没有标准行为,所以你不应该假设所有编译器的行为都是一样的。
https://stackoverflow.com/questions/52701490
复制相似问题