【问题标题】:cannot convert argument 1 from 'std::shared_ptr<ChaseState>' to 'std::shared_ptr<State<Cow>>无法将参数 1 从 'std::shared_ptr<ChaseState>' 转换为 'std::shared_ptr<State<Cow>>
【发布时间】:2016-12-14 23:04:32
【问题描述】:

当试图调用一个方法setCurrentState我得到错误:

StateMachine::setCurrentState(std::shared_ptr>)': 无法将参数 1 从 'std::shared_ptr' 转换为 'std::shared_ptr>'

这表明std::shared_ptr&lt;ChaseState&gt; 不是std::shared_ptr&lt;State&lt;Cow&gt;&gt;,但为什么不是?

函数调用:

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;
};

在我的 StateMachine 中,我有私有变量:

std::shared_ptr<State<entity_type>> m_currentState;

和 setCurrentState 函数:

void setCurrentState(std::shared_ptr<State<entity_type>> s) { m_currentState = s; }

据我了解,派生类 ChaseState 是一个状态(因为它继承自状态)。

【问题讨论】:

    标签: c++ inheritance casting


    【解决方案1】:

    您需要声明您的继承public。默认情况下,类继承是私有的,这意味着您不能从 Derived 转换为 Base,因为在类本身之外无法识别继承(与在类外无法访问私有成员的方式相同)。

    要修复,请将您的继承公开:

    class ChaseState : public State<Cow>
    //                 ^^^^^^
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-20
      • 2023-03-24
      • 2017-08-06
      • 2011-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多