如何在构造函数中创建接口数组
C++: How to create array of interfaces inside constructor
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,所以清理你的对象
相关文章:
- 模板化接口 - 创建一个泛型模板类以返回任何容器
- 类接口,可以创建N个方法
- 在C ++ ASIO中,如何为HTTP或HTTPS创建相同的套接字对象(接口/抽象问题?
- 无法使用 SQL VDI(虚拟设备接口)创建条带化备份
- 如何创建一个接口,允许我访问C++中的按钮(和其他ui)函数,该函数是使用python中的MFC实现的
- 我们可以在层次结构中创建多个纯虚拟接口及其实现而不会代码爆炸吗?
- C++创建具有可变参数模板方法的接口
- 创建接口和混凝土类并在向量中使用它们会导致调用方法时的怪异行为
- 如何在接口类中创建一个超类对象
- 在旧接口上创建新的 C++ 接口以添加新函数
- 在C++中创建接口的对象
- 使用类模板参数推导来创建一个静态接口
- 是否在对象中创建临时接口
- 当从一个应用程序调用时,在DLL方法中创建COM接口指针是有效的,但当从另一个应用软件调用时则无效
- 创建 COM 接口指针在开发计算机上有效,但会导致其他计算机上的应用程序崩溃
- 为我的C++静态库创建接口
- 使用SWIG为perl创建C++接口
- 如何在构造函数中创建接口数组
- 用什么类型的智能指针创建接口
- 如何使用 .NET 为应用程序创建接口C++