1

我目前正在制作一个游戏,它使用一个状态堆栈管理器来跟踪所有不同的游戏状态,比如主菜单。

但是,我遇到了一个我似乎无法解决的问题。

这是状态类,被剥离为只包含有问题的代码:

class StateManager;

namespace first {
namespace second {

class State {
  friend class StateManager;
  protected:
    /**
     * Associates the state with the specified state manager instance.
     * @param stateManager The instance to associate this state with
     */
    void associateWithManager(StateManager *stateManager) {
      mStateManager = stateManager;
    }
  private:
    StateManager *mStateManager;
};

} // second
} // first

以下是状态管理器,也被剥离:

namespace first {
namespace second {

class StateManager {
  public:
    /**
     * Adds a state to the stack.
     * @param state The state to add
     */
    State &add(State &state) {
      state.associateWithManager(this);
      return state;
    }
};

} // second
} // first

当我尝试编译它时,我收到以下错误(行号有点偏离,因为我包含了警卫等):

src/StateManager.cc: In member function 'State& StateManager::add(State&)':
src/StateManager.cc:7:34: error: no matching function for call to 'State::associateWithManager(StateManager* const)'
src/StateManager.cc:7:34: note: candidate is:
In file included from ./include/StateManager.h:4:0,
                 from src/StateManager.cc:1:
./include/State.h:29:10: note: void State::associateWithManager(StateManager*)
./include/State.h:29:10: note:   no known conversion for argument 1 from 'StateManager* const' to 'StateManager*'

显然,this指针被视为 const 指针,即使我没有const在方法上使用关键字add。我不确定这里到底发生了什么。this指针总是吗const?我很确定我过去曾以这种方式使用它,但没有任何问题。

另外,我这样做的方式是“正确”的方式吗?或者在让州政府了解经理方面是否有更好的解决方案?也许使用单例,但我并不是它的忠实粉丝。

编辑:我现在意识到命名空间之外的前向声明是造成这种情况的原因。我应该接受迈克的回答吗,因为它帮助我得出了这个结论?还是我应该发布自己的?

4

2 回答 2

2

这是唯一的错误吗?当我编译它时,我首先得到这个错误:

test.cpp:8:31: error: ‘StateManager’ has not been declared

当将一个类声明为友元时,该类必须已经被声明,否则该声明被忽略。所以你需要class StateManager;在定义之前在周围的命名空间中声明class State. 通过该更改,您的代码将为我编译。

于 2013-04-05T13:59:29.440 回答
1

this指针不是 a StateManager *,它是StateManager * const

尝试将您的论点的常量更改为StateManager* const stateManager

如果你不想修改你的调用函数,你总是可以抛弃常量: state.associateWithManager(const_cast<StateManager*>(this));

于 2013-04-05T14:19:15.673 回答