将“this”作为参数传递时,来自const的“未知转换”

时间:2013-04-05 13:52:03

标签: c++ pointers gcc const

我目前正在开发一款利用状态堆栈管理器的游戏,它可以跟踪所有不同的游戏状态,例如主菜单。

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

这是州级,被剥离为仅包含有问题的代码:

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吗?我很确定我过去用这种方式没有任何问题。

另外,我正在采用'正确'的方式吗?或者,让国家了解经理是否有更好的解决方案?也许使用单身人士,但我并不是真正的粉丝。

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

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:1)

this指针不是StateManager *,而是StateManager * const

尝试将参数的常量更改为StateManager* const stateManager

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

相关问题