尝试调用方法时 setCurrentState
我收到错误:
StateMachine<Cow>::setCurrentState(std::shared_ptr<State<Cow>>)': cannot convert argument 1 from 'std::shared_ptr<ChaseState>' to 'std::shared_ptr<State<Cow>>'
这表示 std::shared_ptr<ChaseState>
不是 std::shared_ptr<State<Cow>>
但为什么不是呢?
调用函数:
std::shared_ptr<ChaseState> initialState = std::make_shared<ChaseState>();
m_stateMachine->setCurrentState(initialState);
State.h
#pragma once
template <class entity_type>
class State
{
public:
virtual void enter(entity_type*) = 0;
virtual void execute(entity_type*) = 0;
virtual void exit(entity_type*) = 0;
};
ChaseState.h
class Cow;
class ChaseState : State<Cow>
{
public:
ChaseState();
// Inherited via State
virtual void enter(Cow*) override;
virtual void execute(Cow*) override;
virtual void exit(Cow*) override;
};
在我的状态机中我有私有(private)变量:
std::shared_ptr<State<entity_type>> m_currentState;
和 setCurrentState 函数:
void setCurrentState(std::shared_ptr<State<entity_type>> s) { m_currentState = s; }
据我了解,派生类 ChaseState 是一个 State(因为它继承自 state)。
最佳答案
您需要声明您的继承public
。默认情况下,类继承是私有(private)的,这意味着您不能从 Derived
转换为 Base
,因为在类本身之外无法识别继承(与无法访问私有(private)成员的方式相同课外)。
要修复,请公开您的继承:
class ChaseState : public State<Cow>
// ^^^^^^
关于c++ - 无法将参数 1 从 'std::shared_ptr<ChaseState>' 转换为 'std::shared_ptr<State<Cow>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41153764/