C++模板类的用法
本文实例讲述了C++模板类的用法,分享给大家供大家参考。具体实现方法如下:
main.h头文件如下:
template<classT> classactioncontainer { public: //构造函数 actioncontainer() { m_nRedoPos=0; m_nUndoPos=0; } //容器的接口函数 voidadd(Tvalue); Tredo(); Tundo(); //容器的属性 private: intm_nRedoPos; intm_nUndoPos; conststaticintACTION_SIZE=5; Tm_RedoAction[ACTION_SIZE]; Tm_UndoAction[ACTION_SIZE]; }; template<classT> voidactioncontainer<T>::add(Tvalue) { if(m_nUndoPos>=ACTION_SIZE) { //如果容器已潢,刚调整添加位置 m_nUndoPos=ACTION_SIZE-1; for(inti=0;i<ACTION_SIZE;i++) { m_UndoAction[i]=m_UndoAction[i+1]; } } m_UndoAction[m_nUndoPos++]=value; } template<classT> Tactioncontainer<T>::redo() { //将恢复动作复制到撤销数组中 m_UndoAction[m_nUndoPos++]=m_RedoAction[--m_nRedoPos]; //返回恢复的动作 returnm_RedoAction[m_nRedoPos]; } template<classT> Tactioncontainer<T>::undo() { m_RedoAction[m_nRedoPos++]=m_UndoAction[--m_nUndoPos]; returnm_UndoAction[m_nUndoPos]; }
main.cpp源文件如下:
//test_iostream.cpp:定义控制台应用程序的入口点。 // #include"StdAfx.h" #include"main.h" usingnamespacestd; int_tmain(intargc,_TCHAR*argv[]) { actioncontainer<int>intaction; //向容器中加动作 intaction.add(1); intaction.add(2); intaction.add(3); intaction.add(4); //撤销上一步动作 intnUndo=intaction.undo(); nUndo=intaction.undo(); //恢复 intnRedo=intaction.redo(); return0; }
希望本文所述对大家的C++程序设计有所帮助。