如何在构造函数中创建接口数组

C++: How to create array of interfaces inside constructor

本文关键字:创建 接口 数组 构造函数      更新时间:2023-10-16

Arduino项目。使用c++ 11编译器。我已经创建了一个"接口"类和几个实现类。我想实施战略模式。在我的策略管理器类中,我想创建一个固定长度的数组,并在构造函数中初始化它。

我正在尝试做的Java示例(在任何现代语言中都应该是小菜一碟,对吧Stroustrup?)

public interface IState {
    public void handle();
}
public class StateImpl implements IState {
    @Override
    public void handle(){
        //Do something
    }
}
public class StrategyManager {
    private IState[] states;
    public StrategyManager(){
        states = new IState[3];
        state[0] = new StateImpl();
        state[1] = new StateImpl();
        ...
    }
}

c++的第一次尝试:

IState.h:

class IState {
    public:
        virtual ~IState() {}
        virtual void handle() = 0;    
};

StateImpl.h:

#ifndef StateImpl_h  
#define StateImpl_h
#include "IState.h"
class StateImpl : public IState {
    public:
        StateImpl();
        virtual void handle() override;
};
#endif

StateImpl.cpp:

#include "StateImpl.h"
StateImpl::StateImpl(){}
void StateImpl::handle(){
    //Do something
}

到目前为止还好。为了简洁起见,我已经简化了我的类,所以代码可能无法编译,但我的可以,现在问题来了:

StrategyManager.h:

#ifndef StrategyManager_h  
#define StrategyManager_h
#include "IState.h"
class StrategyManager {
  private:
     extern const IState _states[3];          
  public:     
      StrategyManager(); 
};
#endif

StrategyManager.cpp:

#include "StrategyManager.h"
StrategyManager::StrategyManager(){    
    IState _states[3] = {
        new StateImpl(),  
        new StateImpl(), 
        new StateImpl()
    };
}

这给了我各种各样的错误:

error: storage class specified for '_states'
error: invalid abstract type 'IState' for '_states' because the following virtual functions are pure within 'IState':
    virtual void IState::handle()
error: cannot declare field 'StrategyManager::_states' to be of abstract type 'IState'
since type 'IState' has pure virtual functions
... etc

所以我将数组改为保存指针。在StrategyManager.h:

extern const IState* _states[3];

现在在StrategyManager.cpp构造器中:

StrategyManager::StrategyManager(){ 
    IState impl = new StateImpl(); //I hope this will be stored in the heap.  
    IState* _states[3] = {
        &impl,  
        &impl, 
        &impl
    };
}

但是仍然有错误:

error: storage class specified for '_states'
error: cannot declare variable 'impl' to be of abstract type 'IState'
since type 'IState' has pure virtual functions

我怎么能做到这一点在一个简单的方式不使用矢量或增强或任何其他花哨的东西?(记住这是Arduino)

它真的比那简单得多,并且更接近您的java代码(只显示相关部分):

class StrategyManager {
  private:
     IState *_states[3];          
  public:     
      StrategyManager(); 
};

StrategyManager::StrategyManager(){    
    _states[0] = new StateImpl();
    _states[1] = new StateImpl();
    _states[2] = new StateImpl();
    };
}

请记住,C/c++不是java,没有GC,所以清理你的对象