Arduino的項目的接口數組。使用C++ 11編譯器。我創建了一個「接口」類和幾個實現類。我想實施stategy模式。在我的策略管理器類中,我想創建一個固定長度的數組並在構造函數中初始化它。 (?並應在任何現代語言,對斯特勞斯小菜一碟)C++:如何創建內部構造
的什麼,我試圖做Java示例
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的)
一個'new'表達式的計算結果爲指針在C++中。 – juanchopanza
爲什麼選擇extern?爲什麼固定大小? – Amit
@juanchopanza如果我不使用new,它會在堆棧中創建,因爲我在構造函數中? –