C++模板类的用法_技术学院_宜昌市隼壹珍商贸有限公司

您好,欢迎访问宜昌市隼壹珍商贸有限公司

400 890 5375
当前位置: 主页 > 新闻动态 > 技术学院

C++模板类的用法

发布时间:2026-01-18  |  点击率:

本文实例讲述了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++程序设计有所帮助。

全国统一服务电话

400 890 5375

电子邮箱:879577@qq.com

公司地址:宜昌市西陵区黄河路5号三峡明珠10栋1051室

咨询微信

TEL:13680874598