C++模板類的用法
更新時間:2014年10月21日 10:21:20 投稿:shichen2014
這篇文章主要介紹了C++模板類的用法,實例講述了模板類的概念及相關用法,需要的朋友可以參考下
本文實例講述了C++模板類的用法,分享給大家供大家參考。具體實現(xiàn)方法如下:
main.h頭文件如下:
復制代碼 代碼如下:
template <class T>
class actioncontainer
{
public:
//構造函數(shù)
actioncontainer()
{
m_nRedoPos = 0;
m_nUndoPos = 0;
}
//容器的接口函數(shù)
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()
{
//將恢復動作復制到撤銷數(shù)組中
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];
}
class actioncontainer
{
public:
//構造函數(shù)
actioncontainer()
{
m_nRedoPos = 0;
m_nUndoPos = 0;
}
//容器的接口函數(shù)
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()
{
//將恢復動作復制到撤銷數(shù)組中
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;
}
//
#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++程序設計有所幫助。
相關文章
C/C++?Qt?給ListWidget組件增加右鍵菜單功能
本篇文章給大家介紹ListWidget組件增加一個右鍵菜單,當用戶在ListWidget組件中的任意一個子項下右鍵,我們讓其彈出這個菜單,并根據(jù)選擇提供不同的功能,感興趣的朋友跟隨小編一起看看吧2021-11-11MATLAB算法技巧和實現(xiàn)斐波那契數(shù)列的解決思路
這篇文章主要介紹了MATLAB算法技巧和實現(xiàn)斐波那契數(shù)列,這篇主要說一下自己在算法設計課上用matlab做的兩道算法題,題目解起來都比較簡單,但是需要些技巧,需要的朋友可以參考下2022-12-12