C++模板類的用法。本站提示廣大學習愛好者:(C++模板類的用法)文章只能為提供參考,不一定能成為您想要的結果。以下是C++模板類的用法正文
本文實例講述了C++模板類的用法,分享給年夜家供年夜家參考。詳細完成辦法以下:
main.h頭文件以下:
template <class T>
class actioncontainer
{
public:
//結構函數
actioncontainer()
{
m_nRedoPos = 0;
m_nUndoPos = 0;
}
//容器的接口函數
void add(T value);
T redo();
T undo();
//容器的屬性
private:
int m_nRedoPos;
int m_nUndoPos;
const static int ACTION_SIZE=5;
T m_RedoAction[ACTION_SIZE];
T m_UndoAction[ACTION_SIZE];
};
template<class T>
void actioncontainer<T>::add(T value)
{
if (m_nUndoPos >= ACTION_SIZE)
{
//假如容器已潢,剛調劑添加地位
m_nUndoPos = ACTION_SIZE - 1;
for(int i = 0; i < ACTION_SIZE; i++)
{
m_UndoAction[i] = m_UndoAction[i+1];
}
}
m_UndoAction[m_nUndoPos++] = value;
}
template<class T>
T actioncontainer<T>::redo()
{
//將恢復舉措復制到撤消數組中
m_UndoAction[m_nUndoPos++] = m_RedoAction[--m_nRedoPos];
//前往恢復的舉措
return m_RedoAction[m_nRedoPos];
}
template<class T>
T actioncontainer<T>::undo()
{
m_RedoAction[m_nRedoPos++] = m_UndoAction[--m_nUndoPos];
return m_UndoAction[m_nUndoPos];
}
main.cpp源文件以下:
// test_iostream.cpp : 界說掌握台運用法式的進口點。
//
#include "StdAfx.h"
#include "main.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
actioncontainer<int> intaction;
//向容器中加舉措
intaction.add(1);
intaction.add(2);
intaction.add(3);
intaction.add(4);
//撤消上一步舉措
int nUndo = intaction.undo();
nUndo = intaction.undo();
//恢復
int nRedo = intaction.redo();
return 0;
}
願望本文所述對年夜家的C++法式設計有所贊助。